我知道我错过了一些东西,但它不起作用,我不知道出了什么问题。这是自定义的防伪属性。
[AttributeUsage(AttributeTargets.Class)]
public class ValidateAntiForgeryTokenOnAllPosts : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.HttpContext.Request;
// Only validate POSTs
if (request.HttpMethod == WebRequestMethods.Http.Post)
{
// Ajax POSTs and normal form posts have to be treated differently when it comes
// to validating the AntiForgeryToken
if (request.IsAjaxRequest())
{
var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
var cookieValue = antiForgeryCookie != null
? antiForgeryCookie.Value
: null;
AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
}
else
{
new ValidateAntiForgeryTokenAttribute()
.OnAuthorization(filterContext);
}
}
}
}
我正在从 ajax 请求发送令牌。
console.log(JSON.stringify(data));
return $.ajax({
url: url,
type: "post",
cache: false,
contentType: "application/JSON; charset=utf-8",
crossDomain: true,
data: JSON.stringify(data),
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Accept", "application/json, text/json, */*");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Authorization", "__RequestVerificationToken token=\"FuHCLyY46\"");
}
在 Asp Master Page 中,我放置了隐藏字段。
<form id="form1" runat="server">
<div>
<input type="hidden" name="__RequestVerificationToken" value="FuHCLyY46"/>
</div>
</form>
但它不起作用。请确定我在做什么错?