ASP.NET MVC防伪令牌(CSRF)不起作用

时间:2019-01-15 10:43:29

标签: asp.net model-view-controller csrf antiforgerytoken

到目前为止,我一直在尝试将CS​​RF令牌添加到我的代码中,到目前为止还算不上运气。我认为有三个步骤:

我要发送的表单的代码:

@using (Html.BeginForm("Manage", "Account"))
{
    @Html.AntiForgeryToken()
}

在控制器视图中,我写了:

public class HomeController : Controller
    {
    [HttpPost]
    [ValidateAntiForgeryToken] 

public ActionResult Index()
    {

        return View("Table");
    } 
    etc...
    }

和我的ajax调用:

$.ajax({
            type: "POST",
            url: "../Home/" + sFunction,
            contentType: "application/json; charset=utf-8",
            processData: false,
            dataType: "json",
            headers: { "__RequestVerificationToken": 
            $('input[name=__RequestVerificationToken]').val() },
            data: data === null ? null : JSON.stringify(data),

我想念什么?为什么它不起作用? 谢谢

1 个答案:

答案 0 :(得分:2)

[ValidateAntiForgeryToken]需要装饰您的表单发布方法。不是您的索引GET方法。在这种情况下...

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Manage(YourViewModel model)
{
    //do your logic

    return View(//whatever route & model)
}

,然后在js中将其添加到数据对象中。

let form = //get your form control here
let data = $(form).serialize();//form is your form control
data.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();

$.ajax({
        type: "POST",
        url: //controller/action,
        contentType: "application/x-www-form-urlencoded",
        processData: false,
        dataType: "json",
        data: JSON.stringify(data),
        //etc....
});