在開發的時候,為客戶端編寫代碼訪問WCF的方式,我們應該比較熟悉,主要是添加一個代理,然后通過這個代理進行訪問。
如果用瀏覽器訪問WCF呢?(其實最終是想在JS里面訪問)用瀏覽器訪問、測試Web Service我們常常干, 而WCF整合了Web Service,Remoting,MSMQ,訪問起來應當會更加方便吧?
一、代碼配置
新建一個WCF服務,系統自動生成契約(即接口文件),代碼文件(*.svc)。在契約文件里,要加上必要的特性
[OperationContract] [WebGet(UriTemplate="/HelloWorld", RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)] string HelloWorld();
SVC文件里,類也要加上相關特性:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Attendance : IAttendance { public string HelloWorld() { return "Hello World!"; } }
類這個特性,貌似也可以寫到配置文件里。
二、配置文件配置
1)配置及原理
配置文件要添加一些節點。下面標注為“手動添加”的,即為需要添加的節點。其余則是系統默認提供。
<system.serviceModel> <behaviors> <serviceBehaviors> <behavior> <!-- 為避免泄漏元數據信息,請在部署前將以下值設置為 false --> <serviceMetadata httpGetEnabled="false" httpsGetEnabled="false"/> <!-- 要接收故障異常詳細信息以進行調試,請將以下值設置為 true。在部署前設置為 false 以避免泄漏異常信息 --> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> <!-- 我們手動添加 --> <endpointBehaviors> <behavior name="webBehavior"> <webHttp /> </behavior> </endpointBehaviors> </behaviors> <protocolMapping> <add binding="basicHttpsBinding" scheme="https" /> </protocolMapping> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> <!-- 我們手動添加 --> <services> <service name="WCF_Mobile.Attendance"> <endpoint behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="WCF_Mobile.IAttendance" /> </service> </services> </system.serviceModel>
這里面的節點含義,我目前並不十分了解。大概是:WCF本身提供服務(Services),外部通過接口,即endpoint(端點)來使用這些服務。然后服務、端點,都有一些約定進行描述,即behavior。
從上述配置文件可以看到,Service下面的endpoint,引用了<endpointBehaviors>的內容。
有關配置文件的一些知識,可以參考
我的WCF之旅(2):Endpoint Overview
http://www.cnblogs.com/artech/archive/2007/02/28/659331.html
WCF配置文件詳解(一)
http://www.cnblogs.com/weichuo/archive/2008/07/09/1238979.html
2)跨域請求問題
不過,要注意,JS訪問WCF,常常有跨域的問題。那么這時候要配置一下WCF的配置文件。詳見拙作:
http://blog.csdn.net/leftfist/article/details/38383049
三、用IIS承載WCF
首先要將WCF發布到一個指定文件夾,然后在IIS里配置此文件夾為網站。
這種發布跟普通asp.net網站發布沒什么兩樣。習慣上,我喜歡發布為文件系統,每個文件一個DLL這種方式。
四、返回值類型用Stream
使用流作為返回值的好處,一是速度似乎比較快,二是如果服務返回string等其他類型,IE瀏覽器下,會有提問框出現,流就沒有這個問題
public Stream Delete() { return GetStream(@"{""data"":""OK!!!!!!""}"); } /// <summary> /// 輔助方法,用於輸出流 /// </summary> /// <param name="str"></param> /// <returns></returns> private Stream GetStream(string str) { MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms); sw.AutoFlush = true; sw.Write(str); ms.Position = 0; WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"; return ms; }