Generate a return Url with a custom AuthorizeAttribute

EvilDr picture EvilDr · Apr 22, 2015 · Viewed 7.2k times · Source

I have a custom authorize attribute:

using System;
using System.Web.Mvc;
using System.Web.Routing;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAuthenticated)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Login", action = "Login" }));
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

...that I use to decorate certain controllers:

[MyAuthorizeAttribute(Roles = "Superman, Batman, Spiderman")]
public class SuperHeroController : Controller
{
    // ....
}

Can anyone please explain how to amend the authorize code so that if authorization fails, the Login URL includes a ReturnUrl (URL of the current controller/method)?

This is basically trying to imitate the web forms ReturnUrl logic but in a smart manner whereby I don't have to manually use a string for the URL.

Answer

EvilDr picture EvilDr · Apr 22, 2015

Finally figured it out, although somebody might be able to suggest a better way...

filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                            {
                                controller = "Login",
                                action = "Login",
                                returnUrl = filterContext.HttpContext.Request.Url.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped)
                            }));