WCF REST 4.0 PUT/POST/DELETE无法正常工作(400 Bad Request)

shu*_*iar 2 asp.net http http-post http-put

我一直在努力在.NET 4.0中设置WCF REST服务.我有GET请求工作,但任何涉及POST数据到服务器的请求都失败了HTTP 400 Bad Request.

这是我的简单服务:

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Service1
{
    [WebGet(UriTemplate = "")]
    public string HelloWorld()
    {
        return "hello world";
    }

    [WebInvoke(UriTemplate = "", Method = "POST")]
    public string HelloWorldPost(string name)
    {
        return "hello " + name;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的Web.config:

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </modules>
  </system.webServer>

  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <protocolMapping>
      <add scheme="http" binding="webHttpBinding" />      
    </protocolMapping>
    <standardEndpoints>
      <webHttpEndpoint>
        <!-- 
            Configure the WCF REST service base address via the global.asax.cs file and the default endpoint 
            via the attributes on the <standardEndpoint> element below
        -->
        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>

</configuration>
Run Code Online (Sandbox Code Playgroud)

我的global.asax:

public class Global : HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes();
    }

    private void RegisterRoutes()
    {
        RouteTable.Routes.Add(new ServiceRoute("Service1", new WebServiceHostFactory(), typeof(Service1)));
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上,一切都是默认的模板,但我只是简化了Service1.我已经尝试通过调试器运行它并通过Fiddler传递请求并在IIS中运行它并执行相同的操作,以及使用简单的控制台应用程序来伪造POST但我总是得到400 Bad Request错误而我不知道为什么.我看过整个互联网,无法解决任何问题.

我已经尝试了以下两个请求示例(都不起作用):

XML:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">String content</string>
Run Code Online (Sandbox Code Playgroud)

JSON:

"String content"
Run Code Online (Sandbox Code Playgroud)

Mar*_*wen 6

Content-Type是否在请求中正确设置了标题?对于XML请求,它应该是text/xmlJSON应该是application/json.当我在Fiddler中设置Content-Type时,您的代码适用于我.

您还应该Accept将GET中的标题设置为text/xml或者application/json取决于您希望响应的格式.可以使用POST,因为服务器会假定您希望响应的格式与请求相同,因为您已automaticFormatSelectionEnabled="true"在web.config中设置.有关WCF REST中格式选择的更多详细信息,请访问:http://blogs.msdn.com/b/endpoint/archive/2010/01/18/automatic-and-explicit-format-selection-in-wcf-webhttp-services的.aspx