4

As a glutton for unproven sexy techniques I've adopted System.Web.Routing in my Web Forms application to manage navigation and such. Further, I'm hoping to move role-based security from web.config to the route definitions itself so I can say "this route is only available to roles x, y".

So I've got the class that implements IRouteHandler and before it attempts to load a particular page it checks to see if the user is in it's set of allowed roles. My question is, if they aren't, how do I redirect to the login page within that handler? I know it's possible to load the login page in that instance, but I'd prefer a clean redirect with the "returnto" page and all.

public IHttpHandler GetHttpHandler(RequestContext requestContext) {

if ( AllowedRoles != null )
{
    bool allowed = false;

    for ( int i = 0; i < AllowedRoles.Length; i++ )
    {
        if ( requestContext.HttpContext.User.IsInRole( AllowedRoles[i] ) )
        {
            allowed = true;
            break;
        }
    }

    if ( !allowed )
    {
        ???
    }
}
Sebastian Weber
  • 6,766
  • 2
  • 30
  • 49
James White
  • 2,062
  • 2
  • 24
  • 36

1 Answers1

4

It's possible to do a redirect from GetHttpHandler. Just use:

requestContext.HttpContext.Response.Redirect("login.aspx");
Rob Volk
  • 5,204
  • 5
  • 25
  • 19
  • Without specifying `endRequest: false` this will cause a `ThreadAbortException` and should not be called. See https://stackoverflow.com/questions/2777105/why-response-redirect-causes-system-threading-threadabortexception and https://blogs.msdn.microsoft.com/tmarq/2009/06/25/correct-use-of-system-web-httpresponse-redirect/ – Dai Sep 25 '19 at 00:05