【问题标题】:How can I read and attribute from the controller/Action in Global.asax如何从 Global.asax 中的控制器/动作中读取和属性
【发布时间】:2016-07-14 09:48:48
【问题描述】:

在 WebApi 2 应用程序中,是否可以从 Global.Asax 文件的 Application_BeginRequest 方法中读取 Action/Controller 的属性?

目前,我能够获取控制器和操作名称,但不知道从那里读取自定义属性的最佳方式。

【问题讨论】:

  • 我也想在 Application_OnPostAuthenticateRequest 方法中的 global.asax 中的 Action 方法上阅读 CustomAttribute?除了反射之外,您还有其他解决方案吗?

标签: asp.net-mvc asp.net-web-api global-asax


【解决方案1】:

解决方案 1

使用反思。

注意:这假设您的所有操作名称对于控制器来说都是唯一的。

如果不是真的,我猜……这个解决方案会惨败。

首先,您需要找到程序集。

这可以通过选择您的 api 控制器之一来完成,例如(它们当然是找到所需程序集的其他几种方法)

var assembly = typeof (HomeController).Assembly;

现在,我猜你得到了控制器动作并以这种方式命名:

var routeData = RouteTable.Routes.GetRouteData(
                new HttpContextWrapper(HttpContext.Current));
var actionName = routeData.GetRequiredString("action");
var controllerName = routeData.GetRequiredString("controller");

所以下一步是获取控制器的类型。 可以通过

//you don't need the full name
var controllerType = assembly.GetTypes().FirstOrDefault(m => m.Name ==  controllerName + "Controller");

var controllerType = assembly.GetType("<namespace>." + controllerName + "Controller");

然后就可以得到控制器的customAttributes

var controllerCustomAttributes = controllerType.GetCustomAttributes();

如果你想要动作属性,你需要获取与你的动作名称对应的方法。

var actionType = controllerType.GetMethods().FirstOrDefault(x => x.Name == actionName );

再一次,获取自定义属性

var actionAttributes = actionType.GetCustomAttributes();

解决方案 2

最好在您的所有操作中添加自定义ActionFilterAttribute,并使用OnActionExecuting

例如,请参阅this

【讨论】:

  • 看起来第一个解决方案非常适合我的用例。我不能使用 ActionFilterAttribute,因为我需要在 AuthorizationFilter 之前执行此代码(希望在这一点上不要遗漏任何东西)。谢谢ndeed Raphaël。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 2013-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多