Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Authorization based on Route Params

My site allows people to edit posts. I want people to only edit their posts. I'd want an authorization attribute like:

[CanEditPost(PostId = Id)]
ActionResult Edit(int Id) { }

But it seems like parameters to attributes have to be static, which makes this impossible. Is there any way to get around this?

like image 641
Xodarap Avatar asked Mar 07 '11 19:03

Xodarap


1 Answers

Yes.

If you create an attribute that inherits from AuthorizeAttribute,

you should be able to access the route parameters by:

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    var postId = httpContext.Request.RequestContext.RouteData.Values["Id"];
    .
    .
    .
}
like image 68
CD.. Avatar answered Nov 09 '22 10:11

CD..