【问题标题】:WCF POST method [duplicate]WCF POST方法[重复]
【发布时间】:2013-12-19 18:13:04
【问题描述】:

{"远程服务器返回错误:(405) Method Not 允许}System.InvalidOperationException {System.Net.WebException}

网页配置:

      <service name="Service" behaviorConfiguration="RestService">      
        <endpoint address="web" binding="webHttpBinding"
                  contract="IService" behaviorConfiguration="ServiceBehavior">
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="RestService">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ServiceBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <!--<protocolMapping>
      <add binding="basicHttpsBinding" scheme="https"/>
    </protocolMapping>-->
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

服务:

    public test TestPost(test testPost)
    {
        test objtest1 = new test();
        objtest1.Address = "Test";
        objtest1.Name = "Welcome";
        return objtest1;
    }


[DataContract]
public class test
{
    [DataMember(Order = 0)]
    public string Name { get; set; }
    [DataMember(Order = 1)]
    public string Address { get; set; }
}


    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare,
       RequestFormat = WebMessageFormat.Json,
       ResponseFormat = WebMessageFormat.Json,
       UriTemplate = "TestPost/")]
    test TestPost(test i);

使用提琴手:

POST /RESTfulService/Service.svc/web/TestPost/ HTTP/1.1
User-Agent: Fiddler
Host: localhost:50458
Content-Length: 43

HTTP/1.1 400 Bad Request
Server: ASP.NET Development Server/11.0.0.0
Date: Thu, 19 Dec 2013 07:19:44 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 1647
Cache-Control: private
Content-Type: text/html
Connection: Close

GET 方法工作正常,当我尝试使用 POST 方法时出现错误

【问题讨论】:

  • 显示您正在发布的实际 XML 请求...看来问题出在请求中,因为其他一切似乎都很好。
  • 我使用的是 Json 格式。格式为 { "Name" = "test", "Address" = "test" }
  • 操作,我错过了。好的,看这个问题:stackoverflow.com/questions/575893/…,好像也一样。
  • 不应该是{"Name" : "test", "Address" : "test"}吗?即: 代替=
  • 只需将内容类型设置为application/json。从给出的提琴手示例中,没有传递任何内容类型。这就是问题所在。

标签: c# wcf


【解决方案1】:

我在本地尝试了上面的示例,发现您缺少一个名为

的 http 标头
Content-Type: application/json

还要确保在请求正文中传递正确的 json 字符串

{"Name" : "test", "Address" : "test"}

以上技巧将帮助您摆脱 400 错误请求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    相关资源
    最近更新 更多