Asp.net

在 ajax post ASP.NET MVC 中包含 antiforgerytoken

  • January 23, 2013

我在使用 ajax 的 AntiForgeryToken 時遇到問題。我正在使用 ASP.NET MVC 3。我在jQuery Ajax 呼叫和 Html.AntiForgeryToken()中嘗試了解決方案。使用該解決方案,現在正在傳遞令牌:

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

當我刪除[ValidateAntiForgeryToken]屬性只是為了查看數據(帶有令牌)是否作為參數傳遞給控制器時,我可以看到它們正在被傳遞。但是由於某種原因,A required anti-forgery token was not supplied or was invalid.當我放回屬性時仍然會彈出消息。

有任何想法嗎?

編輯

antiforgerytoken 是在表單中生成的,但我沒有使用送出操作來送出它。相反,我只是使用 jquery 獲取令牌的值,然後嘗試 ajax 發布它。

這是包含令牌的表單,位於頂部母版頁:

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

您錯誤地指定了contentTypeto application/json

這是一個如何工作的範例。

控制器:

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

   [HttpPost]
   [ValidateAntiForgeryToken]
   public ActionResult Index(string someValue)
   {
       return 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")">
   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>

引用自:https://stackoverflow.com/questions/14473597