POST调用WCF

现在手机端经常会用到不是自己的数据,这个时候就需要用到post请求别的接口来取得数据,所以今天我就记录一下使用POST方式调用WCF

 

1 首先需要在建立好的WCF项目中配置一下web.config,如下

 

<system.serviceModel>
    <services>
      <!--contract为契约接口 name为契约实现类-->
      <service name="WcfService1.Service1">
        <endpoint binding="webHttpBinding"
                  contract="WcfService1.IService1" 
                  behaviorConfiguration="webHttp"/>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webHttp">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <bindings>
      <webHttpBinding>
        <binding>
        </binding>
      </webHttpBinding>
    </bindings>
  </system.serviceModel>


其中红色部分为必要部分

WCF的代码,这里只是做了个测试,所以代码很简单

  public string GetData(string value)
        {
            return string.Format("You entered: {0}", value);
        }

 

 

2 然后在契约方法的头部加上

 

[WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, Method = "POST")]
string GetData(string value);

具体的属性代表什么用的时候都会有提示的

 

3 然后就在客户端调用了,我这里是在电脑端调用,所以还是用C#写的,代码如下

 

  WebClient client = new WebClient();
            client.Headers.Add("Content-Type", "application/json");
            var result = client.UploadString("http://localhost:8010/Service1.svc/GetData", "POST", "{\"value\":\"123\"}");

 

 因为规定了json格式,所以参数必须是json格式的

 

posted @ 2015-07-09 11:04  傲羽寒  阅读(613)  评论(0编辑  收藏  举报