.NET 3.5以后,WCF中提供了WebGet的方式,允许通过url的形式进行Web 服务的访问。在以前的代码中,写过多次类似的例子,但总是忘记如何配置,现在将设置步骤记录如下:
  1. endpoint通讯协议设置成  webHttpBinding
  2. endpoint的行为设置成 <webHttp />
  3. 在接口上加入 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";
 

相关文章:

  • 2021-08-11
  • 2022-01-13
  • 2021-10-19
  • 2021-11-27
  • 2021-11-04
  • 2021-07-13
  • 2022-12-23
  • 2021-10-22
猜你喜欢
  • 2021-07-04
  • 2021-04-29
  • 2021-12-04
  • 2021-09-09
  • 2021-06-30
  • 2021-12-06
  • 2021-11-23
相关资源
相似解决方案