2017-09-28 182 views
1

我正在使用jQuery DataTales從MVC5請求POST URL並嘗試添加防僞標記。我已經將它添加到頭文件和請求正文中,但仍然收到500錯誤:「所需的防僞表單字段」__RequestVerificationToken「不存在。」__RequestVerificationToken與Ajax POST不存在

形式:

<form id="my-units-form" action="@Url.Action("MyUnitsResults", "Provider")" class="form-horizontal criteria well well-sm"> 
    @Html.AntiForgeryToken() 
    .... 

中的JavaScript:

$userDt = $('#users-table') 
    .DataTable({ 
     serverSide: true, 
     ordering: false, 
     searching: true, 
     ajax: { 
      "url": url, 
      "type": "POST", 
      'contentType': 'application/json', 
      "dataType": "json", 
      headers: { '__RequestVerificationToken': $('form input[name=__RequestVerificationToken]').val() }, 
      data: function (d) { 
       d.__RequestVerificationToken= $('form input[name=__RequestVerificationToken]').val(); 

       return JSON.stringify(d); 
      } 
     }, 

Headers

Payload

回答

0

如果喲你將數據字符串化並使用contentType: 'application/json,然後只將該標記添加到ajax標頭(它不會從主體讀取)。

你,那麼你需要創建一個自定義FilterAttribute從頭

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)] 
public sealed class ValidateHeaderAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter 
{ 
    public void OnAuthorization(AuthorizationContext filterContext) 
    { 
     if (filterContext == null) 
     { 
      throw new ArgumentNullException("filterContext"); 
     } 

     var httpContext = filterContext.HttpContext; 
     var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName]; 
     AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]); 
    } 
} 

,並在控制器方法讀取的值,用[ValidateHeaderAntiForgeryToken]

+0

優秀更換[ValidateAntiForgeryToken]屬性!謝謝。 – Echilon

相關問題