c# - 如何从我的 ApiController 中的 ActionFilterAttribute 访问属性?

标签 c# asp.net-web-api

我有一个自定义的 ActionFilterAttribute。为了这个问题,我们假设它如下:

public class CustomActionFilterAttribute : ActionFilterAttribute {
    public bool success { get; private set };

    public override void OnActionExecuting(HttpActionContext actionContext) {
        //Do something and set success
        success = DoSomething(actionContext);
    }
}

我的 Controller 然后用 CustomActionFilter 装饰。我正在寻找的是一种方法(在我的 Controller 方法中)来做类似的事情:

[CustomActionFilter]
public class MyController : ApiController {
    public ActionResult MyAction() {
        //How do I get the 'success' from my attribute?
    }
}

如果有更可接受的方法,请告诉我。

最佳答案

我发现我可以做以下事情来解决我的问题:

[CustomActionFilter]
public class MyController : ApiController {
    public ActionResult MyAction() {
        var myAttribute = ControllerContext
                          .ControllerDescriptor
                          .GetCustomAttributes<CustomActionFilter>()
                          .Single();
        var success = myAttribute.success;
    }
}

关于c# - 如何从我的 ApiController 中的 ActionFilterAttribute 访问属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25310736/

相关文章:

c# - ExecuteNonQuery 在 C# 中不起作用

c# - 获取空错误 LINQ;那么不能使用?

c# - 使用 Autofac 将 SignalR IHubContext 注入(inject) Controller

c#-4.0 - 如何使用 HttpClient 从 Web Api 调用 PUT 方法?

c# - 使用 delegate 和 lambda 在列表中查找匹配元素

c# - ASP.NET 中的缓存控制 header

c# - 添加新列就是删除datagridview的所有现有列

c# - HttpClient in using 语句导致任务取消

c# - 在操作方法中抛出 HttpResponseException 时处理 HttpResponseMessage 及其内容

android - 使用 volley 调用 WebAPI