开发者

asp.net MVC: reroute to action in custom action attribute

i'm trying to create an attribute that i can set on my controllers action in which i can check if a user in some kind of role. I know with standard asp.net authentication this is already possible, but i'm not using that.

So what i want to accomplish is this:

[Role("Admin", "SuperUser")]
public ActionResult SafeCourse()

I've constructed this:

public class AdminAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

Ans now..... i want to re开发者_运维百科direct the user to some controller/action or if that isn't possible to some view when he / she is not in the right role. But i'm not in my usual context (= controller) and i'm somewhat lost :)

Michel


If you make your action filter implement IAuthorizationFilter it will execute before other types ... then in OnAuthorization(AuthorizationContext filterContext) set the result.

Something like

filterContext.Result = new RedirectResult("/Controller/ActionYouWantToDirectTo");

Kindness,

Dan


The proper/correct way of doing this

Asp.net MVC has extensibility point exactly for your needs. You should be writing a custom action method selector attribute that would actually select the correct action method based on the definition in the attribute.

public class RoleAttribute: ActionMethodSelectorAttribute
{
    ...
}

Check this blog post that talks about action method selectors. One of the good extensibility points in Asp.net MVC yet not many developers know about it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜