ActionFilter 未被稱為 WebAPI/.netCore



我有一个用 .NETCore 我想要的只是使用操作过滤器拦截请求,然后从标头中验证 JWT 令牌。我编写了一个动作过滤器,如下所示:

using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
namespace Applciation.ActionFilters
{
public class AuthorizeJWT: ActionFilterAttribute, IActionFilter
{
void IActionFilter.OnActionExecuting(ActionExecutingContext context)
{
var jwt = context.HttpContext.Request.Headers["JWT"];
try
{
var json = new JwtBuilder()
.WithSecret(File.ReadLines("").ToList().First())
.MustVerifySignature()
.Decode(jwt);                    
var tokenDetails = JsonConvert.DeserializeObject<dynamic>(json);
}
catch (TokenExpiredException)
{
throw new Exception("Token is expired");
}
catch (SignatureVerificationException)
{
throw new Exception("Token signature invalid");
}
catch(Exception ex)
{
throw new Exception("Token has been tempered with");
}
}
}
}

现在,我在服务配置中添加了操作过滤器,如下所示:

services.AddScoped<AuthorizeJWT>();

并像下面这样装饰我的控制器:

[AuthorizeJWT]            
public virtual async Task<IActionResult> Ceate([FromBody]CreateDto,createDto)
{
//method body
}

但由于某种原因,我的操作过滤器只是没有被调用。配置中缺少什么吗?

ActionFilter的定义不正确。您只需要从ActionFilterAttribute类派生,而不是从接口IActionFilter派生,因为 ActionFilterAttribute 类已经实现了该接口。

如果从继承中删除接口,然后更改OnActionExecuting方法定义以覆盖基类实现,则一切都将按预期工作:

using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
namespace Applciation.ActionFilters
{
public class AuthorizeJWT: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var jwt = context.HttpContext.Request.Headers["JWT"];
try
{
var json = new JwtBuilder()
.WithSecret(File.ReadLines("").ToList().First())
.MustVerifySignature()
.Decode(jwt);                    
var tokenDetails = JsonConvert.DeserializeObject<dynamic>(json);
}
catch (TokenExpiredException)
{
throw new Exception("Token is expired");
}
catch (SignatureVerificationException)
{
throw new Exception("Token signature invalid");
}
catch(Exception ex)
{
throw new Exception("Token has been tempered with");
}
}
}
}

最新更新