2

given a mvc4 which has a {sitename} parameter in the routes like so

routes.MapRoute(
    "Sites", // Route name
    "{sitename}/{controller}/{action}/{id}", // URL with parameters
    new { sitename = "", controller = "Home", action = "Index", id = "" } // Parameter defaults
);

and all is working well except AccountController and any other which use the [Authorize] attribute as the redirect goes to

 ~/Account/Login 

rather than

 ~/{sitename}/Account/Login 

for consistency and aesthetics as well

Is there a way to change this ? The obvious answer is to create a custom AuthorizeAttribute but most examples such as the answer to ASP.NET MVC 4 custom Authorize attribute - How to redirect unauthorized users to error page? simply call

 base.HandleUnauthorizedRequest();

so looking for any help before i tried the code/debug/code/debug route !

Community
  • 1
  • 1
Kumar
  • 10,997
  • 13
  • 84
  • 134

1 Answers1

0
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        var sitename = filterContext.RouteData.Values["sitename"] as string;
        if (!string.IsNullOrEmpty(sitename))
        {
            var routeValues = new RouteValueDictionary(new
            {
                controller = "account",
                action = "login",
                sitename = sitename,
            });
            filterContext.Result = new RedirectToRouteResult(routeValues);
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928