EvilDr EvilDr - 1 year ago 133
ASP.NET (C#) Question

Generate a return Url with a custom AuthorizeAttribute

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" }));

...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
(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 Source

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

filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                                controller = "Login",
                                action = "Login",
                                returnUrl = filterContext.HttpContext.Request.Url.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download