c# - 我怎样才能得到 Controller 操作的 MethodInfo,它将根据请求被调用?

标签 c# asp.net-mvc-2 asp.net-mvc-routing

我有一个 Controller 和操作负责处理由于用户角色不正确而导致的 403。它可以访问导致异常的原始 RequestContext

我希望能够做的是用他们所做的描述来装饰我的行为,然后允许用户通知他们的经理,请求访问权限,包括在电子邮件中的描述。

那么,在给定 RequestContext 的情况下,我如何确定将调用什么操作?

显然,这比从 RouteData 中获取 Controller 和 Action 名称要复杂得多,因为经常会重载 Action 方法等。

一旦我有了MethodInfo,就很容易获得属性等。

最佳答案

这里有一个扩展方法供您使用。如果您在 Controller (非无参数构造函数)上进行依赖注入(inject),则需要使用反射枚举 Controller 构造函数,或使用 IOC 容器实例化 Controller ,而不是使用 Activator.CreateInstance。此外,可以修改它以很容易地使用类似的上下文,如 ExceptionContext 或 HttpContext。

public static class RequestContextExtensions
{
    public static MethodInfo GetActionMethod(this RequestContext requestContext)
    {
        Type controllerType = Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(x => x.Name == requestContext.RouteData.Values["controller"].ToString());
        ControllerContext controllerContext = new ControllerContext(requestContext, Activator.CreateInstance(controllerType) as ControllerBase);
        ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);
        ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, controllerContext.RouteData.Values["action"].ToString());
        return (actionDescriptor as ReflectedActionDescriptor).MethodInfo;
    }
}

关于c# - 我怎样才能得到 Controller 操作的 MethodInfo,它将根据请求被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10814147/

相关文章:

c# - Windows Phone 8.1 VibrationDevice 不会停止振动

c# - 当数据对于 web.config 来说太大时该怎么办

asp.net - MVC2 路由问题

asp.net - 删除 ASP.NET MVC 4 路由中的尾部斜杠到应用程序根

c# - 在 MVC4 中设置默认 Controller

c# - EF 代码优先 - 获取 DynamicProxies 而不是对象。为什么?

c# - 获取 Silverlight 5 部署路径(在浏览器中以完全信任模式运行时)

asp.net-mvc - MVC 中公共(public) NonAction 方法的用途

asp.net-mvc - Azure Web 角色 - 混合 MVC 和 WCF - 最佳实践

asp.net-mvc-2 - 如何连接多个 MvcHtmlString 实例