views:

33

answers:

2

Hi,

I'm currently using RedirectToRouteResult as follow:

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        User user = filterContext.HttpContext.Session["user"] as User;
        if (user == null || user.Role != expectedRole)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary{ {"controller", _controller}, {"action", _action} });
        }
    }

This code is in my CheckLoginAttribute class.

I intend to use it as decorator on specific controller actions for example:

[CheckLogin(RolesEnum.Member, "MyController", "MyAction")]
public JsonResult GetNews()

So basically, I'm trying to short circuit a call to GetNews() and skip the execution of the action if the user is not logged on. If the user is not logged on then I want it to redirect to another action.

Will "RedirectToRouteResult" redirect to the appropriate action server side without having to do a big loop through the client side (like rewritting window url location or something like that) ? Is that how it works ?

Thanks for the help Appreciated

A: 

No - RedirectXXXResult always returns HTTP 302. This is not an equivalent of Server.Transfer().

Jakub Konecki
A: 

Well, I've figured it out on my own.

So basically, it wasn't "redirection" that I needed. I was looking at the wrong place to solve my problem. I knew that redirection meant that I'd have to make several client/server trips just to be able to return a json result and it didn't feel right.

It took me a while to realize that I can pass any type of result into filterContext.Result.

It's my fault. I wasn't asking the right question because I didn't completely understand the problem I was facing. After a lot of research it comes down to being really stupid.

Final solution is:

    public class CheckLoginAttribute : AuthorizeAttribute, IAuthorizationFilter
{

    private RolesEnum expectedRole;

    public CheckLoginAttribute(RolesEnum role)
    {
        expectedRole = role;
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        User user = filterContext.HttpContext.Session["user"] as User;
        if (user == null || user.Role != expectedRole)
        {
            filterContext.Result = new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new LoginMessage() { IsValidLogin = false }
            };
        }
    }
}

And now I can decorate my action methods with this:

[CheckLogin(RolesEnum.Admin)]

A little bit more code to avoid ASP.NET Session stealing and I'm done.

I hope this will help someone out there. Thanks.

Tchi Yuan