如何阅读自定义控制器属性

如何阅读自定义控制器属性

本文介绍了WebApi iActionFilter实现.如何阅读自定义控制器属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现自定义身份验证过滤器,并使用此处描述的被动属性"方法: http://blog.ploeh.dk/2014/06/13/passive-attributes/

I'm implementing custom authentication filter and using "Passive Attributes" approach described here:http://blog.ploeh.dk/2014/06/13/passive-attributes/

DI可以按预期工作,但是我不知道如何从控制器本身读取自定义属性?我希望单个动作和整个控制器都支持此功能.

DI works as expected but I can't figure out how to read custom attributes from controller itself? I would like both individual actions and whole controllers to support this functionality.

控制器示例:

[TokenAuth] // This attribute not "visible"
public class SupportController : ApiController
{
    private ISecurityService SecurityService { get; }

    public SupportController(ISecurityService securityService)
    {
        this.SecurityService = securityService;
    }

    [TokenAuth] // This attribute works
    [HttpGet]
    public object StartupData()
    {
        return "Startup data";
    }
}

这是我读取自定义属性的过滤器代码的一部分:

This is portion of filter code where I read custom attribute:

public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
    var tokenAuthAttribute = actionContext.ActionDescriptor.GetCustomAttributes<TokenAuthAttribute>(true).SingleOrDefault();

    // This line below exists unless attribute placed on method/action

    if (tokenAuthAttribute == null) return continuation();

    var req = actionContext.Request;

有什么方法可以访问控制器的属性?

Is there any way to access controller's attributes?

推荐答案

动作描述符应该使您可以通过 ControllerDescriptor 属性

The action descriptor should give you access to the controller type via the ControllerDescriptor property

var actionDescriptor = actionContext.ActionDescriptor;

var tokenAuthAttribute =
    actionDescriptor.GetCustomAttributes<TokenAuthAttribute>(true).SingleOrDefault() ??
    actionDescriptor.ControllerDescriptor.GetCustomAttributes<TokenAuthAttribute>(true).SingleOrDefault();

//...

上面的代码首先检查动作描述符,如果什么也没找到,则检查控制器描述符.

The above checks the action descriptor first and if nothing is found then checks the controller descriptor.

这篇关于WebApi iActionFilter实现.如何阅读自定义控制器属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 19:50