zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    List.Foreach与C#的foreach的区别
    他们突然觉得我懂的还挺多,嘎嘎~
    Mysql跨表更新 多表update sql语句总结
    “你没有权限登录JIRA”的解决办法
    iis日志查看
    自已写的Json序列化方法,可以序列话对象的只读属性
    mysql --limit
    python切片
    数据库
    tarzan-linux命令
  • 原文地址:https://www.cnblogs.com/Alex80/p/6928487.html
Copyright © 2011-2022 走看看