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方式訪問了,這么重要的內容一定要寫篇日志記錄一下!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM