简体   繁体   English

不允许使用httpclient post异步返回方法(405)

[英]httpclient post async returning method not allowed (405)

Currently I'm having an issue with posting some data to web api. 目前,我在向Web API发布一些数据时遇到问题。 I have two different project. 我有两个不同的项目。 One project is a web application that is running web api 2.0. 一个项目是运行Web api 2.0的Web应用程序。 The other project is a simple console application that creates a new http client, builds up a json object, and attempts to post it to the web api controller. 另一个项目是一个简单的控制台应用程序,它创建一个新的http客户端,构建一个json对象,然后尝试将其发布到Web api控制器。 However, doing posts I keep getting 405 (Method not allowed...). 但是,在发布帖子时,我不断收到405(不允许使用方法...)。 I've scoured the internet looking for solutions. 我搜寻了互联网以寻找解决方案。 I've even gone as far as checking handlers in IIS Express and comparing that with what I have in web.config. 我什至可以检查IIS Express中的处理程序,并将其与web.config中的内容进行比较。 Still no luck. 仍然没有运气。

So here is what I have for my web api: 所以这是我的Web API的功能:

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

Next, here is my Test model: 接下来,这是我的测试模型:

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

Then, here is a snip of code from my console app that attempts to do the POST: 然后,这是我的控制台应用程序中的一段代码,尝试执行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;
        }

Here is my web.config for 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>

I checked iisexpress applicationhost.config. 我检查了iisexpress applicationhost.config。 Lots of handlers in there, but I'll just post the last few as those seem like the pertinent ones. 那里有很多处理程序,但是我将仅发布最后几个处理程序,因为这些处理程序看起来像是相关的处理程序。 Also note that WebDAV is all commented out everywhere... 还要注意,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>

This constantly returns an http 405. I have other methods in here that perform GETs, and those hit the end points just fine. 这会不断返回http405。在这里,我还有其他执行GET的方法,那些达到终点的方法就很好。

Also worth noting I used an external app to perform a post, such as Postman, sending the raw json in the body. 同样值得注意的是,我使用了外部应用程序来执行发布,例如Postman,将原始json发送到正文中。 And the endpoint was hit! 端点被击中! Seems like it has something to do with the set up of iisexpress, but I could be wrong. 似乎它与iisexpress的设置有关,但我可能是错的。

Anyone have any idea what could be the case? 任何人都知道情况会怎样吗? Or refer me to some link that could uncover the problem? 还是请我参考一些可能会发现问题的链接?

response object I'm getting back from debugging using immediate window: 我正在使用即时窗口从调试中获取响应对象:

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}

Make sure you have inside the <system.webServer> section of the Web.config file of your API project the following: 确保您在API项目的Web.config文件的<system.webServer>部分中具有以下内容:

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

Additionally, in the handlers section: 此外,在处理程序部分:

<handlers>
    <remove name="WebDAV" />
    ...
</handlers>

try this below: Added the ExtensionlessUrlHandler* and added it back. 请尝试以下操作:添加了ExtensionlessUrlHandler*并将其添加回去。 It works for me. 这个对我有用。

  <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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM