0

I am trying to post some simple data with ajax from my view to controller. When I switch it to HttpGet it works fine, but when trying httppost I always get error 400. Here is my view code:

@Html.Hidden("postSettings", Url.Action("MethodName", "MyController")) $.ajax({ url: $("#postSettings").val(), type: "POST", data: JSON.stringify(11), dataType: "json", contentType: "application/json", success: function (_result) { console.log("success") }, error: function (e) { console.log(e); } }); 

And code in my controller:

 [HttpPost] public IActionResult MethodName(object value) { return Ok(); } 

1 Answer 1

1

I did not noticed that I have global filter applied

services.AddMvc(options => { options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); }); 

,adding the CSRF token fixed the problem. I just added this code to my view:

<script type="text/javascript"> function gettoken() { var token = '@Html.AntiForgeryToken()'; token = $(token).val(); return token; } </script> 

And to the ajax request:

headers: { RequestVerificationToken: gettoken() }, 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.