Ajax Call in MVC Core2 Bad Request

对着背影说爱祢 提交于 2019-12-11 00:33:45

问题


I'm refracting a website over to MVC Core 2. For most of my Ajax calls I've been using the .Get() shorthand with no problem. I have one AJAX call that needs to use $ajax() and for some reason I keep getting a bad Request error. Keep in mind this code is currently working in an aspx website (other than the changed url when I refactored).

function get_Data() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Home/Get_Index_Values",
        data: JSON.stringify(),
        dataType: "json"
    }) //End Ajax Call
.Done({})
.fail(function(ts){
alert(ts.response);
})

My method is in the Home Controller for now. With the short hand .get() I've been using this signature with no problem:

public JsonResult Get_Index_Values()
{
 stuff here
}

That didn't work for this $ajax call so I've tried:

      [HttpPost]
    public ActionResult Get_Index_Values()

This also didn't work. I then tried and modified the ajax url to the following and matching the above controller methods signatures (lot of iterations here):

"Home/Get_Index_Values"
/Home/Get_Index_Values
/Get_Index_Values
Get_Index_Values
https://localhost:44339/Home/Get_Index_Values

All to no avail. I can rewrite this to use the shorthand .get(), but I'm interested in getting this to work so I can see what I am doing wrong.


回答1:


Found the problem. I had added a AutoValidateAntiforgeryTokenAttribute in the start up file. Because of this, the tokens were not matching. Had to do the following to make it work:

beforeSend: function (xhr) {
    xhr.setRequestHeader("XSRF-TOKEN",
        $('input:hidden[name="__RequestVerificationToken"]').val());

Got this info from http://www.talkingdotnet.com/handle-ajax-requests-in-asp-net-core-razor-pages/



来源:https://stackoverflow.com/questions/48404961/ajax-call-in-mvc-core2-bad-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!