我一直致力于在 .NET 4.0 中设置 WCF REST 服务。我有 GET 请求工作,但任何涉及向服务器发布数据的请求都会失败,并带有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;
}
}
我的 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>
还有我的 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)));
}
}
基本上,模板中的所有内容都是默认的,但我只是简化了Service1
. 我已经尝试通过调试器运行它并通过 Fiddler 传递请求并在 IIS 中运行它并执行相同的操作,以及使用简单的控制台应用程序来伪造 POST,但我总是收到400 Bad Request
错误,我不知道为什么。我已经在整个互联网上查看,无法弄清楚任何事情。
我已经尝试了以下两个请求示例(均无效):
XML:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">String content</string>
JSON:
"String content"