问题
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