In an ASP.NET MVC project, I have a controller method that accepts POST requests, like so (with the "User" class for completeness):
[HttpPost]
public ActionResult TestMethod(User user)
{
return Content("It worked");
}
public class User
{
public string Name { get; set; }
public string Email { get; set; }
}
I call this method with jQuery Ajax:
$.ajax({
url: '/test/TestMethod/',
data: JSON.stringify({ user: { name: 'NewUserName', email: 'username@email.com' } }),
type: 'POST',
success: function (data) {
alert(data);
},
error: function (xhr) {
alert('error');
}
});
When I create a fresh ASP.NET MVC project, and include this code in a new Test controller, everything works fine. Viewed through Fiddler, a single POST request is made, and I get the controller method return value back.
However, when I run this code in the current MVC project that I'm developing, it doesn't work. From Fiddler I see that the ajax call first initiates a POST method, that gets a 301 http status error ("moved permanently"?). Immeditely afterwards a GET request is made, which generates a 404 not found error (which makes sense as there is no GET action method with this name available).
So I use the exact same code, in a fresh projects and in the existing project, but the code only works in the fresh project. So clearly there's something about my existing project that somehow prevents this from running properly (and causes the odd behaviour of generating both a POST and a GET request). But I have no idea what it could be, so any suggestions welcome...!
Update - routing information:
public static void RegisterRoutes(RouteCollection routes)
{
routes.AppendTrailingSlash = true;
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
Update 2: Looks like this issue is caused by Content Security Policy settings that were switched on for this project.
You need to put the
[FromBody]
annotation before your method's argument.ASP.net MVC framework will use the arguments you pass in the body to recognize the method.
I ran into this issue after I implemented Custom Errors, and My form was posting a File back to the server tthat was larger than the Max Allowed. This resulted in a 404.13 error... I guess that is the default error for "file too large"
When custom errors were turned on all I saw was the 404. It was driving me crazy that I was getting a 404 error when I knew that the request type was a post, and the url where it was posting was correct.
Hope this helps someone.