简体   繁体   English

使用jQuery Ajax的ASP.Net MVC 5无法发送__RequestVerificationToken

[英]ASP.Net MVC 5 using jQuery Ajax unable to send __RequestVerificationToken

I am using MVC 5 with jQuery and am having difficulties with posting the anti forgery token using Ajax. 我将MVC 5与jQuery一起使用,并且在使用Ajax发布防伪令牌时遇到困难。 i have looked on SO at various fixes, but nothing appears to work. 我在各种修复方法上都使用了SO,但似乎没有任何效果。

I have the following code within my view. 我的视图中包含以下代码。

@using (Html.BeginForm("None", "None", FormMethod.Post, new { @id = "js-form" }))
{
    @Html.AntiForgeryToken()
    ....
    other code  
    ....
    <button class="button-primary button expand js-button-search" type="button">Search</button>
}

Then using jQuery I have added an event handler to the button above by selecting the element via the class: js-button-search. 然后使用jQuery,通过类js-button-search选择元素,在上面的按钮中添加了事件处理程序。 The main Ajax call is as per below 主要的Ajax调用如下

$.ajax({
        url: url,
        method: 'POST',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(_self.JsonData),
        success: function (result) {
            // Success code
        },
        error: function (jqXHR, textStatus, errorThrown) {
            // Failure code
        }
    });

Where my confusion is, is around the data parameter. 我困惑的地方是data参数。 I have an object which is populated on demand that contains a large amount of elements that can be used for searching. 我有一个按需填充的对象,其中包含大量可用于搜索的元素。

The object takes the form of (shortened as we current have over 40 search fields): 对象的形式为(缩短了,因为我们当前有40多个搜索字段):

_self.JsonData = { "searchData": {"DocIdFrom" : "426737", "DocIdTo" : "753675", "DocIdTypeSearch" : "between", "DocDateFrom" : "06/02/2017", "DocDateTo" : "", "DocDateTypeSearch" : "greater than", .....
       etc...  
}}

As you can see, the data is parsed using JSON.stringify. 如您所见,数据是使用JSON.stringify解析的。 All of this work as long as the [ValidateAntiForgeryToken] attribute is commented out on the controller function. 只要在控制器功能上将[ValidateAntiForgeryToken]属性注释掉,所有这些工作就可以完成。

Controller as follows: 控制器如下:

[HttpPost]
//[ValidateAntiForgeryToken]
public JsonResult GetSearchResultsJson(SearchCriteria searchCriteria, int? page) 
{
    // code in here
}

When I uncomment the anti forgery attribute, the page stops working. 当我取消注释防伪属性时,页面将停止工作。

Now i know about the need to pass the token across with the post and have tried the following without success: 现在我知道需要在发布时传递令牌,并尝试了以下操作,但均未成功:

how-can-i-supply-an-antiforgerytoken-when-posting-json-data-using-ajax asp-net-mvc-5-ajax-request-on-edit-page-error-requestverificationtoken-is-not 当使用ajax发布json数据时,我如何提供一个防伪令牌 asp-net-mvc-5-ajax请求在编辑页面错误请求验证令牌上没有

The main difference between what I have appears to be a complex object, but i think that is a red herring as Stringify converts the object into a string. 我之间的主要区别似乎是一个复杂的对象,但我认为这是一个红色鲱鱼,因为Stringify将对象转换为字符串。

Sorry, forgot to add. 抱歉,忘记添加。 Fiddler return the following message when the [ValidateAntiForgeryToken] is enabled 启用[ValidateAntiForgeryToken]时,提琴手将返回以下消息

[Fiddler] ReadResponse() failed: The server did not return a complete response for this request. Server returned 0 bytes. 

I would like to thank Stephen Muecke for providing the solution to the problem. 我要感谢Stephen Muecke为该问题提供解决方案。

Firstly my Json object was converted to the following: 首先,我的Json对象被转换为以下内容:

var data = { "__RequestVerificationToken":$('[name=__RequestVerificationToken]').val(),
             "searchData":
             {
                 "DocIdFrom" : "426737", 
                 "DocIdTo" : "753675",
                 ..............
                 etc
             }
           }

Then, I removed the contentType parameter from the Ajax call and stopped stingifying the Json data. 然后,我从Ajax调用中删除了contentType参数,并停止了对Json数据的声明。

This has had the desired effect and now i can call the MVC controller using the [ValidateAntiForgeryToken] attribute. 这已经产生了预期的效果,现在我可以使用[ValidateAntiForgeryToken]属性调用MVC控制器。

You might pass RequestVerificationToken (AntiForgeryToken) on Ajax call by using one of the methods below: 您可以使用以下方法之一在Ajax调用中传递RequestVerificationToken(AntiForgeryToken):

Method I: When using serialize() or FormData() methods, it is not necessary to add the token to the data parameters separately (it will be included id the formdata parameter): 方法I:使用serialize()或FormData()方法时,不必将令牌单独添加到数据参数中(它将包含在formdata参数中):

//Send the values of all form controls within the <form> tags including the token:
var formdata = $('#frmCreate').serialize();
//or
var formdata = new FormData($('#frmCreate').get(0));


Method II: 方法二:

var token = $('[name=__RequestVerificationToken]').val();
$.post(url, { comment: comment, IssueID: postId, __RequestVerificationToken: token }, 
    function (data) { … })

Then you can use the Controller as shown below: 然后,您可以使用控制器,如下所示:

[HttpPost] 
[ValidateAntiForgeryToken]
public JsonResult AddComment(string comment, int IssueID){
    //...
}

Hope this helps... 希望这可以帮助...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM