Azure ASP Web API error 405 method not allowed

2019-08-24 06:06发布

问题:

I have a web api application that I have written and tested locally using VS2017 and IIS Express 10. I am able to POST and GET when running locally using either HTTP or HTTPS. When I publish to Azure I am getting method not allowed on both the post and get over HTTP.

How do I configure the Azure server to allow all the HTTP verbs?

How to configure HTTPS on Azure is another story...

Thanks :-)

回答1:

I'm assuming that your web application uses a js library/framework (react / angular). Usually before the request, they send a preflight CORS request using the "Options" verb. I believe that it's the one that it's being blocked.

One easy way to solve this:

Web.config:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

BaseApiController.cs:

 public class BaseApiController : ApiController
  {
    public HttpResponseMessage Options()
    {
      return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
    }
  }

If it's a cross-domain problem, you can configure CORS directly through Azure portal:

https://docs.microsoft.com/en-us/azure/app-service-api/app-service-api-cors-consume-javascript