WCF使用小結:(1)WCF接收HTTP POST資料的處理方法
在WCF 4.0中,為我們建立Restful API有了更好的支援。通過定義UriTemplate,WebInvoke就可以快速開發API介面。
這裡我記錄一下HTTP POST資料時要如何接收POST過來的資料。
1,方法一:Stream inputStream 輸入流方法(注意看方法
例如我的程式碼
[OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "json/ui/{projectName}/{entityName}?q={queryString}&id={indentity}")] UpdateOrInsertEntityResponse UpdateOrInsertEntityResponse (String projectName, String entityName, String queryString,String indentity,Stream pstream);
UriTemplate定義了引數匹配關係。
"json/ui/{projectName}/{entityName}?q={queryString}&id={indentity}"
對應的引數
String projectName, String entityName, String queryString,String indentity
名稱必須相同,否則不能匹配。所有欄位必須是String型別。
如何獲取POST過來的資料資訊。
定義Stream pstream引數。
如果你現在執行應用程式的話,會在頁面爆出一個錯誤資訊:
System.InvalidOperationException: For request in operation UpdateOrInsertEntityResponse to be a stream the operation must have a single parameter whose type is Stream.
如何解決。
第一步,修改你自己的Service.svc檔案。
將原始的
<%@ ServiceHost Language="C#" Debug="true" Service="Vine.DataMan.RestfulService.EntityService"
CodeBehind="EntityService.svc.cs" %>
增加新的屬性:
Factory="System.ServiceModel.Activation.WebServiceHostFactory"
最後結果是:
<%@
ServiceHost Language="C#"
Debug="true"
CodeBehind="EntityService.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
修改配置檔案Web.config
<system.serviceModel>
<services>
<service name="Vine.DataMan.RestfulService.EntityService">
<endpoint binding="webHttpBinding"
contract="Vine.DataMan.RestfulService.ServiceContracts.IEntityCommonService"
behaviorConfiguration="webHttp"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
注意加粗的文字。必須定義webHttp的行為。