A Simple Guide To ASP.NET routing – let’s redirect!

Redirect relates to the routing In ASP.NET. There are two different ways to routing; or changing the current requests endpoint:

Rewrite the current URL and
Redirect to an external URL.

These two tasks are similar but yet different in their execution.

Rewriting:

Rewriting changes the current request’s path and continues processing the current request with all of it’s existing state through the middleware pipeline. Any middleware registered after the rewrite sees the new URL and processes the remainder of the request with the new path. All of this happens in a single server request. One use case might be Creating ‘prettier URLs’.

For example, here’s how to handle a Rewrite operation in app.Use() middleware:

app.Use(async (context,next) =>
{
    var url = context.Request.Path.Value;

    // Rewrite to index
    if (url.Contains("/home/privacy"))
    {
        // rewrite and continue processing
        context.Request.Path = "/home/index";
    }

    await next();
});

For more complex rewrite and redirect scenarios we can also use the full-fledged ASP.NET Core Rewrite Middleware. Basically it provides the ability to set regEx based rewrites and redirects and a number of different and some common rewrite operations.

Redirecting:

Redirecting actually fires a new request on the server by triggering a new HTTP request in the browser via an 302 Moved or 301 Moved Permanently HTTP Response header. A redirect is an HTTP header response to the client that instructs the client to: Go to the URL I specify in this response header. When we say redirecting; most of the case we refer to this scenario.

A key aspect of the various ways to send a user to another page within an ASP.NET application is where the transfer occurs. That is; whether we handle it within the client browser or on the Web server.

(Client Browser) Response.Redirect:

The Redirect method of the Response object provides a way to implement client-side redirection. The default behavior of the Response.Redirect method is execution of the current page halts, and the user is sent to the new URL. The Web server issues HTTP headers and sends a 302 response to the client browser; this instructs the client to make redirected calls to the target URL. The result is two server requests for each redirection: the original and redirected requests.

(Web Server) Server.Transfer:

The Transfer method of the Server object performs redirection using the server and avoiding HTTP requests. The Server.Transfer method transfers the execution of a target URL to the server and halts execution of the current page. The result is only one request. The server does not notify the client browser of the change. And the page address does not change in the browser. When using Server.Transfer, the target URL must be a virtual path on the same server since the Web server’s worker process is used. The PreviousPage property of the Page class provides code access to properties of the previous page in the browsing session. So Form and querystring variables are persisted between pages.

There are some potential drawback of Server side redirection. For example; The lack of browser interaction with the Server.Transfer method means it may break some AJAX and/or JavaScript functionality. When users refresh a page located via this approach, it can trigger an invalid ViewState error message. While Server.Transfer can cause some user confusion as the URL displayed in the browser address bar is not actually the path that is being executed, it can also lead to some confusion with error logging, as the page URL recorded during logging will display incorrectly.

So most of the cases; the redirect() method is used for redirecting in ASP.NET. There are more or less 4 variations to this process.

Different Types of Redirect:
Redirect()

The first method of redirecting from one URL to another is Redirect(). The Rediect() method is available to controller from the ControllerBase class. It accepts a target URL or where we would like to go. A Simple example might be –

public IActionResult Index()
{
    return Redirect("~/Home/Privacy");
}

public IActionResult Privacy()
{
    return View();
}
RedirectToAction()

The Redirect() method and its variations accept a target URL that can be internal or external to the web application. On the other hand, RedirectToAction() is intended specifically for internal URLs that are based on MVC. The RedirectToAction() method allows us to specify an action name, a controller name, and optionally route values. Consider the following code that uses RedirectToAction() method.

public IActionResult Index()
{
  return RedirectToAction("Privacy", "Home");
}
RedirectToPage()

The RedirectToAction() method and its variants are intended for MVC applications. There is a set of methods intended for Razor Pages applications. The main method from this group i RedirectToPage(). RedirectToPage() method accepts the target Razor Page name. For example, suppose there are two Razor Pages in the Pages folder – Index.cshtml and Privacy.cshtml.
To redirect from Index to Privacy we can write like this in the Onget() page hander of Index :

public IActionResult OnGet()
{
    return RedirectToPage("Privacy");
}
RedirectToRoute()

The RedirectToRoute() method allows us to specify a route name and route values. It then redirects the control to that route.

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/
{action=Index}/{id?}");
});

............................

public IActionResult Index()
{
  return RedirectToRoute("default", 
new { controller = "Home", action = "Privacy" });
}
LocalRedirect()

The LocalRedirect() method is similar to the Redirect() method but can be used to navigate only to the URLs local to our application. That means we can’t redirect to any external / third-party URL using LocalRedirect() method. The LocalRedirect() method returns LocalRedirectResult object and sets the HTTP status code to 302 – Found.

All of the above methods each have 3 variants. They are – Permanent; PreserveMethod and PermanentPreserveMethod. The preserve method is same as original method; but an addition is that they maintain the request method (GET/POST) and also preserves request body.

What is Response.Redirect true and Response.Redirect false?

True and false are the optional parameters of the Redirect methods which decides whether the current page response terminate or not. When we use Response.Redirect("Default.aspx", false) then the execution of current page is not terminated; instead, the code written after the Response.Redirect is executed; and then after that page is redirected to the given page. When we use Response.Redirect("Default.aspx",true); which is by default true; then the execution of current page is terminated and code written after the Response.Redirect is not executed instead of executing code written after the Response.Redirect ,the page is redirected to the given page.

(Note) For mobile pages, if our application relies on cookie-less sessions, or might receive requests from mobile devices that require cookie-less sessions, using a tilde (~) in a path can create a new session and potentially lose session data. To set a property on a mobile control with a path such as “~/path”, we have to resolve the path using ResolveUrl “~/path” before assigning it to the property.

Happy Coding!