martinoss martinoss - 2 months ago 29
C# Question

Azure Mobile App - Getting 405 (Method Not Allowed) when trying POST

I'm trying to migrate my Azure Mobile Service .NET backend to an Azure Mobile App.

I was using some custom Web Api controllers, and after migration I'm getting a

405 (Method Not Allowed)
/
The requested resource does not support http method 'POST'.
error when trying to POST to a controller method that worked before.

I spent hours trying diffent CORS settings but I had no success so far.

This is how I currently configure Web Api:

HttpConfiguration config = new HttpConfiguration();

new MobileAppConfiguration()
.UseDefaultConfiguration()
.ApplyTo(config);

var cors = new EnableCorsAttribute("*", "*","*");
//var cors = new EnableCorsAttribute("*", "*","GET,POST,DELETE,HEAD,PUT,PATCH,OPTIONS");
config.EnableCors(cors);

config.Routes.MapHttpRoute(
name: "Rest",
routeTemplate: "rest/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

config.MapHttpAttributeRoutes();


The controller looks like that:

[Authorize]
[RoutePrefixAttribute("rest/companies")]
public class CompaniesController : ApiController
{
[HttpPost]
[Route("my-active")]
//[EnableCors("*","*","*")]
public HttpResponseMessage SetActive(/*[FromBody]*/Company company)
{
// Implementation
}
}


What I tried too:


  • Set CORS settings in web.config (custom headers / different settings), eg.
    <add name="Access-Control-Allow-Methods" value="GET,POST,DELETE,HEAD,PUT,PATCH,OPTIONS" />

  • Added a cors message handler according this blog post

    (http://blog.bittercoder.com/2012/09/09/cors-and-webapi/)

  • This handler is also removed:
    <remove name="OPTIONSVerbHandler" />



One thing I noticed is, that a Azure Mobile App component seems to override the allowed methods and allowed headers that I configured using
config.EnableCors(cors)
. I was only able to control all settings using web.config and the message handler. But it did not solve the 405 problem anyway.

At this point, I'm not sure if it's a CORS problem at all.

Any ideas? It's currently hard to find good documentation on Mobile Apps and I would appreciate if the .NET backend part would be open sourced... It's somewhat of a black box for me.

Answer

OMG, I found the problem with my code. I had to swap this two statements:

// Needs to be called before MapHttpRoute
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
    name: "Rest",
    routeTemplate: "rest/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

As I was using Azure Mobile Services, calling MapHttpAttributeRoutes caused an error 'An item with the same key has already been added', so I removed that line. I had to re-insert it for Azure Mobile Apps again in order to get attribute routing to work, but I did it at the wrong place, so be careful.