您的位置:首页 > 其它

WCF 的 WebGet 方式

2015-09-28 16:53 211 查看
.NET 3.5以后,WCF中提供了WebGet的方式,允许通过url的形式进行Web 服务的访问。在以前的代码中,写过多次类似的例子,但总是忘记如何配置,现在将设置步骤记录如下:

endpoint通讯协议设置成 webHttpBinding

endpoint的行为设置成 <webHttp />

在接口上加入 WebGet 的Attributes

示例代码如下: web.config文件的配置

<system.serviceModel>
<services>
<service name="Services.ShowerService">
<endpoint binding="webHttpBinding" behaviorConfiguration="WebBehavior" contract="Services.IShowerService" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

WCF接口的设置,这里加入了对URI模板(UriTemplate)和JSON(WebMessageFormat.Json)的支持:

namespace Services
{
[ServiceContract]
public interface ShowerService
{
[OperationContract]
[WebGet(UriTemplate="/Hello/{name}", RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
string Hello(string name);
}
}

测试:打开IE浏览器,在地址栏输入:http://localhost:3000/Services/ShowerService.svc/hello/abc,将会看到访问后的结果。 调试:将Web.config中的 <webHttp /> 修改为 <webHttp helpEnabled="true" />将可以在浏览器页面中列举出可用接口,并提供提交的数据样例。打开IE浏览器,在地址栏输入:http://localhost:3000/Services/ShowerService.svc/help 即可。 Siverlight 访问:使用SL的WebClient访问WebInvoke方法时,不要忘记将 HttpRequestHeader.ContentType 设置成 application/json,代码如下所示:

WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/json";
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: