【问题标题】:Use attribute routing parameters for other attributes对其他属性使用属性路由参数
【发布时间】:2016-06-08 14:13:17
【问题描述】:

我使用属性路由 (MVC) 来调用控制器方法以及具有自定义属性的授权属性:

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

UserAuth 只是一个简单的 AuthorizationAttribute:

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

现在我想将它与 projectId 的参数一起使用。以下代码不起作用,但应该显示我想要实现的目标(我不能只添加 id)

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

【问题讨论】:

  • 不要将 id 传递给UserAuth。而是从Request 对象中获取它。如果您希望灵活地将 id 传递或不传递给UserAuth,则可以使参数为空,如果它为空,则在Request 中查找它。

标签: c# asp.net-mvc asp.net-mvc-5 attributes custom-attributes


【解决方案1】:

您不需要从 AuthorizationAttribute 传递 id。你可以从请求中得到它。

你的动作看起来像

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

在你的属性类中,你可以获取路由值。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    相关资源
    最近更新 更多