ASP MVC jQuery $ .ajax POST request does not call the controller method, but works in the "new" MVC project

In an ASP.NET MVC project, I have a controller method that accepts POST requests, for example (with the class "User" 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 using 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 new ASP.NET MVC project and include this code in a new test controller, everything works fine. Looking through Fiddler, one POST request is executed, and I return the return value of the controller.

However, when I run this code in the current MVC project that I am developing, it does not work. From Fiddler, I see that the ajax call first initiates the POST method, which receives a 301 http status error ("constantly moving"?). Immediately after that, a GET request is executed, which generates a 404 not found error (which makes sense, since there is no way GET can act with this name).

Therefore, I use the same code in new projects and in an existing project, but the code only works in a new project. It is so clear that there is something in my existing project that somehow prevents it from working properly (and causes the odd behavior of generating both the POST and the GET request). But I have no idea what it could be, so any suggestions are 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: This problem appears to be caused by the content security policy settings that were included for this project.

0
source share
2 answers

You need to put the [FromBody] annotation before the method argument.

 [HttpPost] public ActionResult TestMethod([FromBody]User user) { return Content("It worked"); } 

The ASP.net MVC framework will use the arguments you pass in the body to recognize the method.

0
source

I ran into this problem after I implemented custom errors and my form sent the file back to a server that was larger than Max Allowed. This led to error 404.13 ... I think this is the default error for "file too large"

When custom errors were turned on, all I saw was 404. It drove me crazy that I was getting a 404 error when I knew that the request type is the message and the URL where it was posted was correct .

Hope this helps someone.

0
source

All Articles