Search code examples
asp.net-mvcasp.net-mvc-4authorizationaction-filterauthorize-attribute

ASP.NET MVC - How can I get the Namespace In Custom Authorization Filter?


I have to implement the Custom Authorization Filter.

(for check Is Authorized, need Namespace, Controller Name, And Action Name)

I don't manage to Get the Namespace. Here's my code:

ExampleController.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

              ...
          }
     }
}

How can I get the Namespace?

Many thanks in advance.


Solution

  • Convention over configuration

    If you Observance this you can easy get ExampleProject.Controllers because all controller in Controllers folder and if you don't change manually this convention you Safely to get controller's namespace but if you change namespace

       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);
            }
    
    
        }