C#POST / PUT到WCF服务

时间:2018-08-11 17:05:24

标签: c# wcf

所以我尝试将简单的POST请求发送到我的服务并读取响应,但是我收到了错误的请求错误。 这是客户代码

static public async Task<string> PostDataAsync(string service)
{
    string result = null;
    using (WebClient client = new WebClient())
    {

        byte[] response =
        client.UploadValues(service, new NameValueCollection()
        {
            { "name", "SomeName" }
        });

        string result = System.Text.Encoding.UTF8.GetString(response);
        Console.Write(result);
    }

    return result;
}

在服务器端

[OperationContract]
[WebInvoke(Method ="POST", UriTemplate ="TestPUT")]
public byte[] TestPOST(string name)
{
    string str = "Hello" + name + "!";
    byte[] response = System.Text.Encoding.UTF8.GetBytes(str);

    return response;
}

配置文件

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="Service.Updater">
        <endpoint contract="Service.Updater" binding="basicHttpBinding" address="soap" />
        <endpoint contract="Service.Updater" binding="webHttpBinding" address="" behaviorConfiguration="RESTBehavior" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="RESTBehavior">
          <webHttp helpEnabled="true" automaticFormatSelectionEnabled="true" />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <!--<modules runAllManagedModulesForAllRequests="true"/>-->
    <directoryBrowse enabled="true" />
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
  </system.webServer> 
</configuration>

不知道这是否重要,但是GET请求可以正常工作。 PUT和POST请求返回400错误。请求形成相关吗?

0 个答案:

没有答案