如何从.net core中的控制器动作中的动作过滤器访问对象?

时间:2018-08-30 15:09:25

标签: c# asp.net-web-api asp.net-core attributes

在我正在构建的网络api中,一些控制器具有一些动作,这些动作接收来自React的jwttoken作为参数,如下所示。

public async Task<IActionResult> post(string token)
        {
            if (!string.IsNullOrEmpty(token))
            {
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);

                var jsonDecoded = decoder.Decode(token);
                var jwtObject = JsonConvert.DeserializeObject<JwtToken>(jsonDecoded);
//do some business logic
}

很多方法都重复了相同的代码,通过对令牌进行解码来对其进行检查,然后自己承担进一步的责任。

我已经创建了一个身份验证过滤器

public class AuthenticateFilter : Attribute,IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            throw new NotImplementedException();
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            IJsonSerializer serializer = new JsonNetSerializer();
            IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);

            var token = context.HttpContext.Request.QueryString.HasValue ? context.HttpContext.Request.QueryString.Value.Substring(7):String.Empty;
            var jsonDecoded = decoder.Decode(token);
            var jwtObject = JsonConvert.DeserializeObject<JwtToken>(jsonDecoded);
        }
    }

我已经在startup.cs中注册了此过滤器

services.AddMvc(
                options =>
                {
                    options.Filters.Add(new AuthenticateFilter());
                    options.Filters.Add(typeof(AuthenticateFilter));
                }

                ).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

我正在使用一个库对令牌进行解码。 https://github.com/jwt-dotnet/jwt

在过滤器中对令牌进行解码之后,我将json字符串反序列化为.net类,如下所示。

public class JwtToken
    {
        [JsonProperty("sub")]
        public Guid Sub { get; set; }

        [JsonProperty("aud")]
        public string Aud { get; set; }
}

如何访问对象

 var jwtObject = JsonConvert.DeserializeObject<JwtToken>(jsonDecoded);

在我装饰属性的所有控制器操作中。

在旁注中,有没有更好的解决方法,欢迎提出建议。

2 个答案:

答案 0 :(得分:1)

我认为您做得很好,但是不明白为什么需要访问该对象。

如果我很严厉,您应该捕获异常以决定是否应该执行活动。

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.0</version>
    <configuration>
        <suiteXmlFiles>
            <file>src/test/resources/testng.xml</file>
            <file>src/test/resources/testng1.xml</file>
        </suiteXmlFiles>
        <properties>
            <property>
                <name>suitethreadpoolsize</name>
                <value>2</value>
            </property>
            <property>
                <name>surefire.testng.verbose</name>
                <value>10</value>
            </property>
        </properties>
    </configuration>
</plugin>

希望对您有所帮助。

答案 1 :(得分:0)

我找到了一种解决方法,即将对象添加到字典中

context.HttpContext.Items.Add("jwt", jwtObject);

可以通过

在控制器中访问
this.HttpContext.Items.ContainsKey("jwt")