ActionFilter未被称为WebAPI / .netCore

时间:2018-06-05 01:21:00

标签: asp.net-web-api asp.net-core .net-core asp.net-web-api2 action-filter

我有一个用.NETCore编写的webAPI应用程序,我想要的是使用动作过滤器拦截请求,然后在标题中验证JWT令牌。我编写了一个ActionFilter,如下所示:

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
}

但由于某种原因,我的动作过滤器才被调用。我在配置中遗漏了什么吗?

1 个答案:

答案 0 :(得分:4)

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");
            }
        }
    }
}