I am working on ASP.NET Zero which is built on ASP.NET Core. I was getting a bad request error when I used KendoUI Upload control on one of my pages. After lot of research and investigation, I realized the HTTP POST Ajax request is failing with 400 bad request error. My code samples below have some commented line for other scenarios I test. None of the existing posts in stack over flow solved my issue. I Below is my ajax call:
$.ajax({
url: "/test/TestCall",
type: 'Post',
/* data: JSON.stringify({ "Param1": "test" }),
dataType:"json",
processData: false, */// tell jQuery not to process the data
contentType: "application/json", // tell jQuery not to set contentType
success: function (result) {
var res = result;
},
error: function (jqXHR) {
var z = 3;
},
complete: function (jqXHR, status) {
var x = 10;
}
});
My Controller code is: I also tried without extending from MyTestProjectControllerBase and just using the Controller base class. It did not work.
public class TestController : MyTestProjectControllerBase
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult TestCall()
{
//return Content("Name is:" );
return new ContentResult() { Content = "test" };
}
}
What am I missing? I tried using postman and I see this additional information 'Request cannot be fulfilled due to bad syntax'
could not figure it out after spending good 8 hours on this issue. Not sure if the issue is with Asp.net core or asp.net zero. Any pointers would be greatly appreciated.
Update after checking the comments by shyju: Startup.cs file has the following code that enables AntiForgeryTokenAttribute
services.AddMvc(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
Updates to the ajax call and view based on answer by shyju:
$("#backBtn").on("click", function (e) {
var t = $("input[name='__RequestVerificationToken']").val();
$.ajax({
url: "/test/TestCall",
type: 'Post',
/* data: JSON.stringify({ "Param1": "test" }),
dataType:"json",
processData: false, */
contentType: "application/json",
headers: {
"RequestVerificationToken": t
},
success: function (result) {
var res = result;
},
error: function (jqXHR) {
var z = 3;
},
complete: function (jqXHR, status) {
var x = 10;
}
});
});
My view looks like this now:removed rest of the html
<div id="container">
@Html.AntiForgeryToken()
<div class="k-edit-field label">Vendor Name</div>
</div
In Core -- make sure your <form>
tag includes method="post"
.
The method is required to invoke the form tag helper which automatically adds the antiforgery token to the form. (I accidentally left off the method and didn't notice because I was ajax-posting it.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With