我必须实现自定义授权过滤器。
(检查是否已获得授权,需要命名空间,控制器名称和操作名称)
我无法获取命名空间。这是我的代码:
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
...
}
}
}
如何获取命名空间?
非常感谢提前。
答案 0 :(得分: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);
}
}