我有以下自定义方法来验证防伪令牌。
public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
public const string UNAUTHORIZED_TEXT = "Unauthorized";
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
throw new ArgumentNullException("filterContext");
var request = filterContext.HttpContext.Request;
if (request.IsAjaxRequest())
{
var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
var cookieValue = antiForgeryCookie != null ? antiForgeryCookie.Value : null;
AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
}
}
}
我在视图中具有以下令牌
<div class="NewWt" id="PageType" style="margin-top:10px;display:none;float:left;">
<span id="i18n-13">@Model.SaveAsNewWtText</span>
<input id="chkBoxWelcome" type="checkbox" checked="checked">
<span>@Model.WelcomeText</span>
<input id="chkBoxHub" type="checkbox">
<span>@Model.HubText</span>
**<span>@Html.AntiForgeryToken()</span>**
</div>
我在我的post
方法之上称呼它
[HttpPost]
[ValidateJsonAntiForgeryToken]
[Route("api/WT")]
[AllowAnonymous]
public WT Post([FromBody]Widget widget, [FromUri]string pageType)
{ ..... }
我在ValidateJsonAntiForgeryToken
中放置了一个断点,但是断点没有被命中。 filter方法没有被调用。我什至在RegisterGlobalFilters
的{{1}}方法中注册了它,但仍然没有被调用。我在做什么错了?
答案 0 :(得分:0)
考虑到其签名,您似乎已经实现了MVC授权过滤器:
public override void OnAuthorization(AuthorizationContext filterContext)
https://docs.microsoft.com/en-us/previous-versions/aspnet/web-frameworks/dd492255%28v%3dvs.100%29
WebAPI授权过滤器实现名称相同但来自不同名称空间的接口,并且过滤器方法签名应为
public override void OnAuthorization(HttpActionContext filterContext)
https://docs.microsoft.com/en-us/previous-versions/aspnet/web-frameworks/mt175049(v%3dvs.118)
MVC筛选器将永远无法在WebAPI管道中工作,反之亦然。尽管我承认,过滤器名称/接口的相似性可能令人困惑。