WCF 的 WebGet 方式

.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";

public interface IPortalService {

/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
[OperationContract]
[WebGet(UriTemplate = "/Hello?name={name}&sex={sex}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
  string Hello ( string name, string sex );
}

http://localhost:8082/PortalService.svc/Hello?name=Alex&sex=%E5%A5%B3

原文地址:https://www.cnblogs.com/Alex80/p/6928487.html