1

我必须实现自定义授权过滤器。

(检查Is Authorized,需要Namespace、Controller Name和Action Name)

我没有设法获取命名空间。这是我的代码:

示例控制器.cs:

namespace ExampleProject.Controllers 
{
    public class ExampleController : Controller 
    {
        [CustomAuth()]              
        public string Index() 
        {        
            return "OK";
        }
    }
}

CustomAuthFilter.cs:

namespace ExampleProject.Infrastructure.Filters
{
     public class CustomAuthAttribute : AuthorizeAttribute 
     {
          protected override bool AuthorizeCore(HttpContextBase httpContext) 
          {
              string currentNamespace = string.Empty;
              string currentController = string.Empty;
              string currentAction = string.Empty;

              var routeData = httpContext.Request.RequestContext.RouteData;

              currentController = routeData.GetRequiredString("controller"); //Example
              currentAction = routeData.GetRequiredString("action");         //Index

              currentNamespace = How???????   // ExampleProject.Controllers

              ...
          }
     }
}

如何获得命名空间?

提前谢谢了。

4

1 回答 1

0

约定优于配置

如果您遵守这一点,您可以轻松获得 ExampleProject.Controllers,因为 Controllers 文件夹中的所有控制器,如果您不手动更改此约定,您可以安全地获取控制器的命名空间,但如果您更改命名空间

   public class CustomAuthAttribute : AuthorizeAttribute
    {
        public string controllerFullName { get; set; }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string currentNamespace = string.Empty;
            string currentController = string.Empty;
            string currentAction = string.Empty;

            var routeData = httpContext.Request.RequestContext.RouteData;

            currentController = routeData.GetRequiredString("controller"); //Example
            currentAction = routeData.GetRequiredString("action"); //Index
             currentNamespace = controllerFullName.Substring(0, controllerFullName.IndexOf("." + currentController, System.StringComparison.Ordinal));

            return false;
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            controllerFullName = filterContext.Controller.ToString();
            base.OnAuthorization(filterContext);
        }


    }
于 2013-03-02T11:03:15.277 回答