开发者

Authorize current user against controller and action name in ASP.NET MVC 3

开发者 https://www.devze.com 2023-02-23 05:04 出处:网络
I need to create a customized authorization in ASP.NET MVC 3. Inside the app, authorization is defined in 5 tables: users, groups, usergroups, rights, grouprights. A user can belong to several groups,

I need to create a customized authorization in ASP.NET MVC 3. Inside the app, authorization is defined in 5 tables: users, groups, usergroups, rights, grouprights. A user can belong to several groups, and each right can be assigned to several groups too. Each controller action is assigned a RightID.

The built in authorization can't accomodate this setup, so I tried to create a customized AuthorizeAttribute. When overriding AuthorizeCore, I realized I don't have access to controller name and action name.

Can I somehow ask the router to parse the Request.RawUrl inside AuthorizeCore to get controller and action name? Or开发者_运维百科 is there another way to do what I want?


protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    var routeData = httpContext.Request.RequestContext.RouteData;
    var controller = routeData.GetRequiredString("controller");
    var action = routeData.GetRequiredString("action");
    ...
}


You can achieve this using Action Filters where you have access to all HttpContex.

public class MyAuthorizeAttribute : ActionFilterAttribute, IAuthorizationFilter
{

    #region Implementation of IAuthorizationFilter

    public void OnAuthorization(AuthorizationContext filterContext)
    {
              // ... implementation

              // filterContext.Controller is the controller
              // filterContext.RouteData is all the route data
0

精彩评论

暂无评论...
验证码 换一张
取 消