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.