在 ajax post ASP.NET MVC 中包含 antiforgerytoken [英] include antiforgerytoken in ajax post ASP.NET MVC

查看:28
本文介绍了在 ajax post ASP.NET MVC 中包含 antiforgerytoken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 ajax 时遇到了 AntiForgeryToken 的问题.我正在使用 ASP.NET MVC 3.我在 jQuery Ajax 调用中尝试了解决方案和 Html.AntiForgeryToken().使用该解决方案,现在正在传递令牌:

var data = { ... }//带令牌,key 是 '__RequestVerificationToken'$.ajax({类型:POST",数据:数据,数据类型:json",传统:真实,contentType: "application/json; charset=utf-8",网址:我的网址,成功:功能(响应){...},错误:函数(响应){...}});

当我删除 [ValidateAntiForgeryToken] 属性只是为了查看数据(带有令牌)是否作为参数传递给控制器​​时,我可以看到它们正在传递.但是由于某种原因,A required anti-forgery token 未提供或无效. 当我放回属性时仍然弹出消息.

有什么想法吗?

编辑

antiforgerytoken 是在表单内生成的,但我没有使用提交操作来提交它.相反,我只是使用 jquery 获取令牌的值,然后尝试通过 ajax 发布该值.

这是包含令牌的表单,位于顶部母版页:

@Html.AntiForgeryToken()</表单>

解决方案

您错误地将 contentType 指定为 application/json.

这是一个可能如何工作的示例.

控制器:

公共类 HomeController : 控制器{公共 ActionResult 索引(){返回视图();}[HttpPost][验证AntiForgeryToken]公共 ActionResult 索引(字符串 someValue){返回 Json(new { someValue = someValue });}}

查看:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" })){@Html.AntiForgeryToken()}<div id="myDiv" data-url="@Url.Action("Index", "Home")">单击我向控制器操作发送 AJAX 请求用 [ValidateAntiForgeryToken] 属性修饰

<script type="text/javascript">$('#myDiv').submit(function () {var form = $('#__AjaxAntiForgeryForm');var token = $('input[name="__RequestVerificationToken"]', form).val();$.ajax({url: $(this).data('url'),类型:'POST',数据: {__RequestVerificationToken:令牌,someValue: '一些价值'},成功:功能(结果){警报(结果.someValue);}});返回假;});

I am having trouble with the AntiForgeryToken with ajax. I'm using ASP.NET MVC 3. I tried the solution in jQuery Ajax calls and the Html.AntiForgeryToken(). Using that solution, the token is now being passed:

var data = { ... } // with token, key is '__RequestVerificationToken'

$.ajax({
        type: "POST",
        data: data,
        datatype: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        url: myURL,
        success: function (response) {
            ...
        },
        error: function (response) {
            ...
        }
    });

When I remove the [ValidateAntiForgeryToken] attribute just to see if the data (with the token) is being passed as parameters to the controller, I can see that they are being passed. But for some reason, the A required anti-forgery token was not supplied or was invalid. message still pops up when I put the attribute back.

Any ideas?

EDIT

The antiforgerytoken is being generated inside a form, but I'm not using a submit action to submit it. Instead, I'm just getting the token's value using jquery and then trying to ajax post that.

Here is the form that contains the token, and is located at the top master page:

<form id="__AjaxAntiForgeryForm" action="#" method="post">
    @Html.AntiForgeryToken()
</form>

解决方案

You have incorrectly specified the contentType to application/json.

Here's an example of how this might work.

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(string someValue)
    {
        return Json(new { someValue = someValue });
    }
}

View:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()
}

<div id="myDiv" data-url="@Url.Action("Index", "Home")">
    Click me to send an AJAX request to a controller action
    decorated with the [ValidateAntiForgeryToken] attribute
</div>

<script type="text/javascript">
    $('#myDiv').submit(function () {
        var form = $('#__AjaxAntiForgeryForm');
        var token = $('input[name="__RequestVerificationToken"]', form).val();
        $.ajax({
            url: $(this).data('url'),
            type: 'POST',
            data: { 
                __RequestVerificationToken: token, 
                someValue: 'some value' 
            },
            success: function (result) {
                alert(result.someValue);
            }
        });
        return false;
    });
</script>

这篇关于在 ajax post ASP.NET MVC 中包含 antiforgerytoken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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