Search code examples
ajaxasp.net-mvc-routingcross-site

How do I handle an MVC Cross site POST?


I have to handle Cross site POSTS from Ajax calls in an MVC project.

I have a method in my controller that is supposed to accept a POST with the view model as the POST body. My page is making an ajax call to it from Javascript. This works fine if everything is under the same domain.

IE11 sends an OPTIONS request without a POST body the first time my Ajax call is made. MVC tries to route this, fails to find my method (probably because it takes the ViewModel parameter), and returns a 404. However after the first time the call errors out, subsequent calls include the POST body and are routed successfully.

I thought I could fix this easily by including an overload of my method in my controller that takes no parameters and returns a 200 (or 204) and no message body. However this gives me "The current request for action on controller type is ambiguous between the following action methods" and lists both overloads.

What is the best way to get this to route correctly? If I got to my controller method with a null ViewModel, I could return a 200/204 and probably be okay - but I don't get there, routing sends back a 404.


Solution

  • Solved this. CORS requires 2 things, you need all responses to include the Access-Control-Allow-Origin header, and you need to response to OPTIONS requests (either with a 200 or 204).

    My OPTIONS requests were not routing correctly, returning a 404 with the Access-Control-Allow-Origin header, which caused the error but allowed the next request to work without an OPTIONS request.

    I had to handle the OPTIONS requests in my Global.asax.cs