HttpClient异步Post方法返回“方法不允许”(405)错误

4

目前我在向Web API发布一些数据时遇到了问题。我有两个不同的项目。一个项目是运行Web API 2.0的Web应用程序。另一个项目是一个简单的控制台应用程序,它创建了一个新的HTTP客户端,构建了一个JSON对象,并尝试将其发布到Web API控制器。然而,我一直在做发布操作时都会得到405(方法不允许...)的错误。我已经在互联网上寻找解决方案。我甚至已经检查了IIS Express中的处理程序,并将其与web.config中的内容进行了比较。但仍然没有运气。

所以这就是我的Web API:

[RoutePrefix("api/media")]
[Authorize]
public class MultimediaController : ApiController
{
    [HttpPost, Route("test")]
    public IHttpActionResult Store([FromBody] TestRequest request) {
        return Ok(request);
    }
...

接下来,这是我的测试模型:

public class TestRequest {
    public string testProp1 { get; set; }
    public string testProp2 { get; set; }
}

然后,这里是我的控制台应用程序中一段试图进行POST的代码片段:
        private const string testUrl = "/api/media/test/";

        private async Task<bool> RunPostTest()
        {
            var httpClient = CreateHttpClient();
            var content = JsonConvert.SerializeObject(new TestRequest {testProp1 = "hello", testProp2 = "world"});
            var jsonContent = new StringContent(content, Encoding.UTF32, "application/json");

            var response = await httpClient.PostAsync(testUrl, jsonContent);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Response code: {response.StatusCode}");
                return false;
            }

            return true;
        }

这是我的handlers的web.config配置:

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>

我查看了iisexpress应用程序宿主配置文件。那里有很多处理程序,但我只会发布最后几个,因为那些似乎是相关的。还要注意的是,在任何地方都注释掉了WebDAV...

        ...
        <add name="TRACEVerbHandler" path="*" verb="TRACE" modules="ProtocolSupportModule" requireAccess="None" />
        <add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" requireAccess="None" />
        <add name="ExtensionlessUrl-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
        <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
        <add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0" />
        <add name="StaticFile" path="*" verb="*" modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule" resourceType="Either" requireAccess="Read" />
    </handlers>
</system.webServer>

这个代码一直返回一个http 405错误。我这里有其他执行GET请求的方法,它们可以正常地访问端点。
值得注意的是,我使用了一个外部应用程序来执行POST请求,例如Postman,在请求体中发送了原始JSON数据。而且端点也被访问到了!似乎与iisexpress的设置有关,但我可能错了。
有人知道可能是什么问题吗?或者可以给我一些链接来揭示这个问题吗?
使用即时窗口进行调试时,我得到的响应对象如下:
response
{StatusCode: 405, ReasonPhrase: 'Method Not Allowed', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Pragma: no-cache
  X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcZ204NDBkXERvY3VtZW50c1xQcm9qZWN0c1xWaXN1YWwgU3R1ZGlvIFByb2plY3RzXEdpdFxNb2JpbGl0eSBDT0VcU0JWVFxTQlZUXFNCVlRcYXBpXG1lZGlhXHRlc3Rc?=
  Cache-Control: no-cache
  Date: Mon, 16 Jan 2017 17:39:32 GMT
  Server: Microsoft-IIS/10.0
  X-AspNet-Version: 4.0.30319
  X-Powered-By: ASP.NET
  Content-Length: 1218
  Allow: POST
  Content-Type: text/html
  Expires: -1
}}
    Content: {System.Net.Http.StreamContent}
    Headers: {Pragma: no-cache
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcZ204NDBkXERvY3VtZW50c1xQcm9qZWN0c1xWaXN1YWwgU3R1ZGlvIFByb2plY3RzXEdpdFxNb2JpbGl0eSBDT0VcU0JWVFxTQlZUXFNCVlRcYXBpXG1lZGlhXHRlc3Rc?=
Cache-Control: no-cache
Date: Mon, 16 Jan 2017 17:39:32 GMT
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
}
    IsSuccessStatusCode: false
    ReasonPhrase: "Method Not Allowed"
    RequestMessage: {Method: POST, RequestUri: 'http://localhost:45106/api/media/test/', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
  Accept: application/json
  Content-Type: application/json; charset=utf-32
  Content-Length: 164
}}
    StatusCode: MethodNotAllowed
    Version: {1.1}

1
你能发布错误详情吗? - Roman
是的...我将在即时窗口中添加响应对象结果。 - dvsoukup
2个回答

1

请确保在您的API项目的Web.config文件的<system.webServer>部分中包含以下内容:

<modules runAllManagedModulesForAllRequests="true">
    <remove name="WebDAVModule"/> <!-- add this -->
</modules>

此句话的英文原文翻译为:此外,在处理程序部分:
<handlers>
    <remove name="WebDAV" />
    ...
</handlers>

1
我已经添加了这些,但仍然收到相同的405错误。 - dvsoukup

0

尝试以下操作:添加ExtensionlessUrlHandler*并将其添加回去。对我来说有效。

  <modules runAllManagedModulesForAllRequests="true">
    <remove name="WebDAVModule" />
  </modules>
    <handlers>
      <remove name="WebDAV" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接