MVC 5 中显示 ValidateAntiForgeryToken 的 NullReferenceException

NullReferenceException showing for ValidateAntiForgeryToken in MVC 5

我正在尝试在 MVC 5 中使用 ajax 保存数据。当我 posting 表单数据没有 @Html.AntiForgeryToken() 时,它工作得很好。但它向我显示 Object reference not set to an instance of an object 使用 @Html.AntiForgeryToken() 的错误。这是我的 ajax 代码:

$.ajax({
    type: "POST",
    url: "/Employees/Create",
    data: data,
    async: false,
    success: function (result) {
        if (result == 1) {
            window.location.href = '/Employees';
        }
        else {
            $('#error-span').html('Error in insert.');
        }
    },
    error: function () {
        alert('Failed');
    }
});

这是我的控制器方法:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Address,JoinDate,DoB,Gender,BloodGroup,Email,LastName,FirstName,Mobile,UpdateDate,UpdatedBy,Status,EmployeeType,CreatedBy,CreateDate,DesignationId")] EmpDetail empDetail)
{
    try
    {
        Regex rgx = new Regex("[^a-zA-Z0-9 - .]");
        empDetail.FirstName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(rgx.Replace(empDetail.FirstName, "").ToLower()).Trim();
        empDetail.LastName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(rgx.Replace(empDetail.LastName, "").ToLower()).Trim();
        empDetail.Email = empDetail.Email.ToLower().Trim();
        empDetail.UpdateDate = DateTime.Now;
        empDetail.CreatedBy = 234;
        empDetail.CreateDate = DateTime.Now;
        empDetail.UpdatedBy = 234;
        empDetail.Status = 1;

        if (ModelState.IsValid)
        {
            db.EmpDetails.Add(empDetail);
            db.SaveChanges();
            return Json(1);
        }
        else
        {
            return Json(2);
        }
    }
    catch (Exception e)
    {
        return Json(e.Message);
    }
}

发生这种情况是因为数据是通过 JSON 而不是 HTML 表单数据发送的。您应该尝试在 headers 中传递令牌。例如:

查看:

<script>
    @functions{
        public string TokenHeaderValue()
        {
            string cookieToken, formToken;
            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return cookieToken + ":" + formToken;                
        }
    }

    $.ajax("api/values", {
        type: "post",
        contentType: "application/json",
        data: {  }, // JSON data goes here
        dataType: "json",
        headers: {
            'RequestVerificationToken': '@TokenHeaderValue()'
        }
    });
</script>

控制器:

void ValidateRequestHeader(HttpRequestMessage request)
{
    string cookieToken = "";
    string formToken = "";

    IEnumerable<string> tokenHeaders;
    if (request.Headers.TryGetValues("RequestVerificationToken", out tokenHeaders))
    {
        string[] tokens = tokenHeaders.First().Split(':');
        if (tokens.Length == 2)
        {
            cookieToken = tokens[0].Trim();
            formToken = tokens[1].Trim();
        }
    }
    AntiForgery.Validate(cookieToken, formToken);
}

来源:https://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks