我指的是以下链接,用于在我的网络应用程序中实施防伪。
$.ajaxAntiForgery({
type: "POST",
url: "sampleapp",
contentType: false,
processData: false,
cache: false,
success: function (result) { }
});
令牌是按照文档中的描述创建的,但在代码隐藏中它会在下面的行中引发错误。
public abstract class BaseController : Controller
{
private readonly ValidateAntiForgeryTokenAttribute _validator;
private readonly AcceptVerbsAttribute _verbs;
protected BaseController (HttpVerbs verbs)
{
this._verbs = new AcceptVerbsAttribute(verbs);
this._validator = new ValidateAntiForgeryTokenAttribute();
}
protected override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride();
if (this._verbs.Verbs.Contains(httpMethodOverride, StringComparer.OrdinalIgnoreCase))
{
this._validator.OnAuthorization(filterContext);
}
}
}
答案 0 :(得分:0)
请尝试使用此功能。
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class ValidateTokenAttribute : FilterAttribute, IAuthorizationFilter
{
public string VariableTokenKey = "__RequestVerificationToken";
public void OnAuthorization(AuthorizationContext filterContext)
{
try
{
if (filterContext.HttpContext.Request.IsAjaxRequest()) { this.ValidateRequestHeader(filterContext.HttpContext.Request); }
else { AntiForgery.Validate(); }
}
catch
{
InvalidRequest(filterContext, "103", "", "Token not found.");
}
}
private void ValidateRequestHeader(HttpRequestBase request)
{
string cookieToken = string.Empty;
string formToken = string.Empty;
string tokenValue = request.Headers[this.VariableTokenKey]; // read the header key and validate the tokens.
if (!string.IsNullOrEmpty(tokenValue))
{
var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
cookieToken = antiForgeryCookie != null ? antiForgeryCookie.Value : null;
}
AntiForgery.Validate(cookieToken, tokenValue); // this validates the request token.
}
private void InvalidRequest(AuthorizationContext filterContext, string errorCode, string sMessage, string eMessage)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new JsonResult
{
Data = new { ErrorCode = errorCode, Message = eMessage },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
ViewDataDictionary viewData = new ViewDataDictionary();
viewData.Add("ShortMessage", "Access denied.");
viewData.Add("Message", "Anti forgery token not found.");
filterContext.Result = new ViewResult { MasterName = "", ViewName = "Error", ViewData = viewData };
}
}
}