405 method not allowed Web API

前端 未结 21 1466
栀梦
栀梦 2020-11-27 18:33

This error is very common, and I tried all of the solutions and non of them worked. I have disabled WebDAV publishing in control panel and added this to my web config file:<

相关标签:
21条回答
  • 2020-11-27 18:36

    [HttpPost] is unnecessary!

    [Route("")]
    public void Post(ProductModel data)
    {
        ...
    }
    
    0 讨论(0)
  • 2020-11-27 18:37

    You are POSTing from the client:

    await client.PostAsJsonAsync("api/products", product);
    

    not PUTing.

    Your Web API method accepts only PUT requests.

    So:

    await client.PutAsJsonAsync("api/products", product);
    
    0 讨论(0)
  • 2020-11-27 18:37

    My problem turned out to be Attribute Routing in WebAPI. I created a custom route, and it treated it like a GET instead of WebAPI discovering it was a POST

        [Route("")]
        [HttpPost] //I added this attribute explicitly, and it worked
        public void Post(ProductModel data)
        {
            ...
        }
    

    I knew it had to be something silly (that consumes your entire day)

    0 讨论(0)
  • 2020-11-27 18:38

    check in your project .csproj file and change

    <IISUrl>http://localhost:PORT/</IISUrl>
    

    to your website url like this

    <IISUrl>http://example.com:applicationName/</IISUrl>
    
    0 讨论(0)
  • 2020-11-27 18:39

    I could NOT solve this. I had CORS enabled and working as long as the POST returned void (ASP.NET 4.0 - WEBAPI 1). When I tried to return a HttpResponseMessage, I started getting the HTTP 405 response.

    Based on Llad's response above, I took a look at my own references.

    I had the attribute [System.Web.Mvc.HttpPost] listed above my POST method.

    I changed this to use:

    [System.Web.Http.HttpPostAttribute]
    [HttpOptions]
    public HttpResponseMessage Post(object json)        
    {
        ...
        return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
    }
    

    This fixed my woes. I hope this helps someone else.

    For the sake of completeness, I had the following in my web.config:

    <httpProtocol>
        <customHeaders>
            <clear />
            <add name="Access-Control-Expose-Headers " value="WWW-Authenticate"/>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, PATCH, DELETE" />
            <add name="Access-Control-Allow-Headers" value="accept, authorization, Content-Type" />
            <remove name="X-Powered-By" />
        </customHeaders>
    </httpProtocol>
    
    0 讨论(0)
  • 2020-11-27 18:40

    Make sure your controller inherits from Controller class.

    It might even be crazier that stuff would work locally even without that.

    0 讨论(0)
提交回复
热议问题