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

偶尔善良 提交于 2019-11-29 17:10:46

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/5594726/authorize-current-user-against-controller-and-action-name-in-asp-net-mvc-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!