我有一个具有这些属性的端点:
[HttpPost]
[ValidateAntiForgeryToken]
[Route("[controller]/[action]")]
当我全局应用IgnoreAntiforgeryTokenAttribute
时
.AddMvc(opts =>
{
opts.Filters.Add(typeof(CustomExceptionFilter));
opts.Filters.Add(new IgnoreAntiforgeryTokenAttribute());
// or
opts.Filters.Add(typeof(IgnoreAntiforgeryTokenAttribute));
})
它没有禁用该[ValidateAntiForgeryToken]
,但是当我做了类似的事情时:
[HttpPost]
[ValidateAntiForgeryToken]
[IgnoreAntiforgeryToken]
[Route("[controller]/[action]")]
然后就被禁用了,为什么?
最佳答案
对于内置的 ValidateAntiForgeryToken
,您无法通过 Startup.cs
中的 IgnoreAntiforgeryTokenAttribute
禁用它。您可以引用Default order of execution 。
要解决此问题,您可以实现自己的 ValidateAntiforgeryTokenAuthorizationFilter
,例如
public class CustomValidateAntiforgeryTokenAuthorizationFilter : ValidateAntiforgeryTokenAuthorizationFilter
{
public CustomValidateAntiforgeryTokenAuthorizationFilter(IAntiforgery antiforgery, ILoggerFactory loggerFactory)
:base(antiforgery, loggerFactory)
{
}
protected override bool ShouldValidate(AuthorizationFilterContext context)
{
var filters = context.Filters;
if (filters.Where(f => f.GetType() == typeof(IgnoreAntiforgeryTokenAttribute)) != null)
{
return false;
}
else
{
return base.ShouldValidate(context);
}
}
}
并通过 ValidateAntiforgeryTokenAuthorizationFilter
进行注册,例如
services.AddMvc(options => {
options.Filters.Insert(0, new IgnoreAntiforgeryTokenAttribute());
options.Filters.Add(typeof(WebApiExceptionFilter)); // by type
});
services.AddScoped<ValidateAntiforgeryTokenAuthorizationFilter, CustomValidateAntiforgeryTokenAuthorizationFilter > ();
关于c# - 全局应用 IgnoreAntiforgeryTokenAttribute 不会禁用 ValidateAntiForgeryToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56187976/