全局设置ValidateAntiForgeryToken可以通过以下步骤实现:
public class ValidateAntiForgeryTokenFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var method = context.HttpContext.Request.Method;
if (HttpMethods.IsPost(method) || HttpMethods.IsPut(method) || HttpMethods.IsDelete(method) || HttpMethods.IsPatch(method))
{
var antiForgeryService = context.HttpContext.RequestServices.GetService<IAntiforgery>();
var tokenSet = antiForgeryService.GetAndStoreTokens(context.HttpContext);
if (!tokenSet.FormToken.HasValue || !tokenSet.HeaderName.HasValue)
{
context.Result = new BadRequestResult();
return;
}
if (!antiForgeryService.ValidateRequestAsync(context.HttpContext).Result)
{
context.Result = new BadRequestResult();
return;
}
}
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(options =>
{
options.Filters.Add(new ValidateAntiForgeryTokenFilter());
});
}
<form asp-action="Create">
@Html.AntiForgeryToken()
<input type="hidden" name="__RequestVerificationToken" value="@Html.AntiForgeryToken()">
<!-- 其他表单元素 -->
<input type="submit" value="创建" />
</form>
$.ajax({
type: "POST",
url: "/Home/Create",
data: {
__RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
// 其他数据
},
success: function (response) {
// 处理成功的情况
},
error: function (response) {
// 处理失败的情况
}
});
通过以上步骤,可以全局设置ValidateAntiForgeryToken,确保所有需要验证的请求都能被正确验证。
领取专属 10元无门槛券
手把手带您无忧上云