在我的自定义授权属性代码中,我想确定调用了哪个 WebAPI 方法。

我很感激我可以通过传递名称来做到这一点(参见示例 2),但我宁愿不必这样做。

// Example1
[CustomAuthAttribute]
public MyResponse get(string param1, string param2)
{
    ...
}
// in the prev example I would like to be able to identify the
// method from within the CustomAuthAttribute code


// Example2
[CustomAuthAttribute(MethodName = "mycontroller/get")]
public MyResponse get(string param1, string param2)
{
    ...
}
// in this example I pass the controller/method names to the
// CustomAuthAttribute code

有没有办法我可以以某种方式拿起它?

最佳答案

如果从 AuthorizeAttribute 派生,您可以通过 ActionDescriptor 访问 HttpActionContext

public class CustomAuthAttribute : AuthorizeAttribute {
    public override void OnAuthorization(HttpActionContext actionContext) {
        var actionDescriptor = actionContext.ActionDescriptor;
        var actionName = actionDescriptor.ActionName;
        var controllerName = actionDescriptor.ControllerDescriptor.ControllerName;
        //MethodName = "mycontroller/get"
        var methodName = string.Format("{0}/{1}", controllerName, actionName);
    }
}

关于c# - 获取从授权属性调用的 api 方法的名称,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47435233/

10-09 01:22