MVC Core2错误请求中的Ajax调用 [英] Ajax Call in MVC Core2 Bad Request

查看:80
本文介绍了MVC Core2错误请求中的Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将网站改版为MVC Core2.对于我的大多数Ajax调用,我一直使用.Get()速记没有问题.我有一个需要使用$ ajax()的AJAX调用,由于某种原因,我一直收到错误的Request错误.请记住,此代码当前在aspx网站上运行(重构后更改的URL除外).

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);
})

我的方法现在在Home Controller中.用.get()的快捷方式,我一直在使用这个签名没有问题:

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
}

这对于$ ajax通话不起作用,所以我尝试了:

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

      [HttpPost]
    public ActionResult Get_Index_Values()

这也不起作用. 然后,我尝试将ajax网址修改为以下内容,并匹配上述控制器方法签名(此处有很多迭代):

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

全部无济于事.我可以使用速记.get()重写它,但是我对使它起作用很感兴趣,这样我就可以知道我在做错什么.

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.

推荐答案

发现了问题.我在启动文件中添加了AutoValidateAntiforgeryTokenAttribute.因此,令牌不匹配.必须执行以下操作才能使其正常工作:

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());

http:获取此信息://www.talkingdotnet.com/handle-ajax-requests-in-asp-net-core-razor-pages/

这篇关于MVC Core2错误请求中的Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆