Use attribute routing parameters for other attributes

荒凉一梦 提交于 2019-12-13 06:08:00

问题


I use Attribute Routing (MVC) to call Controller Methods and also an Authorizationattribute with custom Properties:

[Route("{id:int}")]
[UserAuth(ProjectId=3)]
public ActionResult Select(int id) {  
    return JsonGet(Magic.DoSomethingMagic());
}

UserAuth is just a simple AuthorizationAttribute:

public class UserAuthAttribute:AuthorizeAttribute {
    public int ProjectId { get;set;}
    protected override bool AuthorizeCore(HttpContextBase contextBase) {
        var currentProject=new Project(ProjectId);
        return currentProject.UserIsMember()
    }       
}

Now I want to use this with a parameter for the projectId. The following code does not work but should show what I want to achieve (I cannot just add the id)

[Route("{id:int}")]
[UserAuth(ProjectId=id)]
public ActionResult Select(int id) {  
    return JsonGet(Magic.DoSomethingMagic());
}

回答1:


you don't need to pass id from your AuthorizationAttribute. you can get it from request.

your action will look like

 [Route("{id:int}")]
        [UserAuth]
        public ActionResult Select(int id)
        {
            return View();
        }

And inside your attribute class, you can get route values.

public class UserAuthAttribute: AuthorizeAttribute
    {
        public int ProjectId { get; set; }
        protected override bool AuthorizeCore(HttpContextBase contextBase)
        {
            var getRouteData =contextBase.Request.RequestContext.RouteData.Values["id"];
            if(getRouteData != null)
            {
                ProjectId = Int32.Parse(getRouteData.ToString());
            }
            if(ProjectId > 5)
            {
                return true;
            }
            else
            {
                return false;
            }           
        }
    }


来源:https://stackoverflow.com/questions/35633488/use-attribute-routing-parameters-for-other-attributes

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