​WCF配置后支持通过URL进行http方式调用​

最近遇到一个小型项目,主要就是通过手机写入NFC信息,思考许久后决定就写一个简单的CS程序来搞定这个问题,可是当涉及到手机和PC通信的时候首先考虑到的就是IIS,同时因为数据库是SQLite,思前想后感觉IIS有点大材小用了,最后决定采用WinForm作为WCF的宿主的方式来提供接口进行数据交互。

于是奋笔疾书没有半天的时间就把PC边的基本功能完成了,这时候就考虑android调用了,此时才发现原来WCF的调用和普通的http完全不同,根本无法通过url传方法名和参数的方式调用,于是经过一系列的查找,终于在茫茫互联网中找到了答案,先说几个重点吧。

第一、app.config的配置,全局代码如下:

 

<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<connectionStrings>
<add name="dbSqlite" connectionString=""/>
</connectionStrings>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="NFCInfo.Services.NFCService">
<endpoint address="" binding="webHttpBinding" contract="NFCInfo.Services.INFCService"
behaviorConfiguration="webBehavior">
<identity>
<dns value="localhost" />
</identity>
</endpoint>

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8008/NFCService/" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>


 

1.httpGetEnabled必须要设置为true

2.endpointBehaviors节点是后来新增且必须的

3.注意名称webBehavior的对应关系

4.http://localhost:8008/NFCService/ 地址可以自己配置,注意端口不要冲突

 

第二、WCF接口必须增加标记

[OperationContract]

[WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]

String Test(String name);

1.WebGet表示通过get方式访问,WebInvoke表示通过post方式访问

2.BodyStyle设置为Bare就直接返回结果,如果设置为Wrapped将会自动增加些内容

3.ResponseFormat有xml和json两种方式

 

通过上面两个地方的配置之后就能够轻松的通过http方式访问了,这么重要的内容一定要写篇日志记录一下!