Advanced Ajapa Yoga Kriyas and Meditations for Software Developers : Tap the power of breath, mantra, mudra, and dhyana for improved focus, peace of mind, and blissful inner connection.


Various ways of redirecting a request in ASP.NET Core

ASP.NET Core web applications often need to redirect a request to another resource based on some condition. There are multiple ways in which you can accomplish this task in ASP.NET Core MVC and Razor Pages. To that end this article discusses them with examples.

Redirect() method

The first method od redirecting from one URL to another is Redirect(). The Rediect() method is available to your controller from the ControllerBase class. It accepts a target URL where you would like to go. For example, consider the following two actions of HomeController.

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

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

The Index() action invokes the Redirect() method by specifying the URL of the Privacy() action. The Redirect() method returns RedirectResult object. This method sets the HTTP status code to 302 - Found and also sets the location header to the target URL. The browser then performs the redirection as per this information.

If you run the Index() action in the browser and press F12 you will see these details:

As you can see, the Request URL shows the original URL entered in the browser. The Status Code is 302 - Found. The 302 status code indicates that requested resource (/Home/Index) is temporarily moved to the URL as indicated by Location header (/Home/Privacy).

The Redirect() method is commonly used when you want to navigate to a URL rather than an action. The Redirect() also allows you to navigate to any URL that is not part of your web application.

RedirectPermanent() method

The second method is RedirectPermanent(). It is similar to the Redirect() method but returns HTTP status code 301 - Moved Permanently. The 301 status code is mainly useful to search engines and SEO tools and indicates that the resource has been permanently moved to the new destination as indicated by the Location header.

As you can see from the above figure, the original URL that was requested is /Home/Index. The browser received 301 status code and the new URL (/Home/Privacy) is specified by the Location header.

The return value of RedirectPermanent() is RedirectResult object with its Permanent property set to true.

RedirectPreserveMethod() method

The RedirectPreserveMethod() method is similar to Redirect() method except that it maintains the request method (GET / POST) and sets HTTP status code to 307 - Temporary Redirect. For example, if your original request was a POST request and contained request body, RedirectPreserveMethod() will use the same HTTP method (and body) while redirecting to the target URL.

Suppose that your Index view contains this form:

<form asp-controller="Home" 
asp-action="Index" method="post">
    <input type="hidden" 
name="guid" value="@Guid.NewGuid()" />
    <button type="submit">Submit</button>
</form>

As you can see, the form is being POSTed to the Index() action and contains a GUID stored in a hidden form field.

Your Index() action now looks like this:

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

And your Prinacy() action looks like this:

public IActionResult Privacy(Guid guid)
{
    return View();
}

If you run the application and submit the form, you will get the following outcome:

As you can see, the original request to /Home/Index is now a POST request. The Location header is pointing to /Home/Privacy.

Upon reaching the Privacy() action you will get the GUID back because it exists in the POST request body.

So, RedirectPreserveMethod() not only preserves the HTTP method but also the request body.

The return value of RedirectPreserveMethod() is RedirectResult object with its PreserveMethod property set to true.

RedirectPermanentPreserveMethod() method

The RedirectPermanentPreserveMethod() method acts similar to RedirectPreserveMethod() discussed above but it returns HTTP status code of 308 - Permanent Redirect.

RedirectToAction() method

The Redirect() method and its variations discussed above 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 you to specify an action name, a controller name, and optionally route values. Consider the following code that uses ReadirectToAction() method instead of Redirect().

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

Here, the first parameter is the target action and the section parameter is the name of the controller housing the target action. If the target action belongs to the same controller as that of the source then the controller name can be omitted.

The return value of RedirectToAction() is RedirectToActionResult object. This object instructs the browser about the HTTP status code and Location header. For example, the above redirection is reflected in the browser as shown below:

As you can see, RedirectToAction() sets the HTTP status code to 302 - Found.

RedirectToActionPermanent(), RedirectToActionPreserveMethod(), and RedirectToActionPermanentPreserveMethod() methods

Just like the Redirect() method variations, the RedirectToAction() also comes with the same set of variations. The RedirectToActionPermanent() returns HTTP status code of 301. The RedirectToActionPreserveMethod() preserves the request method (GET / POST) and sets the HTTP status code to 307. And RedirectToActionPermanentPreserveMethod() preserves the HTTP method and also sets the HTTP status code to 308.

RedirectToPage() method

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 is RedirectToPage(). As you might have guessed the 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 you would write this in the Onget() page hander of Index :

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

The RedirectToPage() method returns RedirectToPageResult object and sets the HTTP status code to 302 - Found.

After running the above code your browser would reflect this :

As you can see, the original request is /Index and the destination is /Privacy.

RedirectToPagePermanent(), RedirectToPagePreserveMethod(), and RedirectToPagePermanentPreserveMethod() methods

Just like the Redirect() method variations, the RedirectToPage() also comes with the same set of variations. The RedirectToPagePermanent() returns HTTP status code of 301. The RedirectToPagePreserveMethod() preserves the request method (GET / POST) and sets the HTTP status code to 307. And RedirectToPagePermanentPreserveMethod() preserves the HTTP method and also sets the HTTP status code to 308.

RedirectToRoute() method

The RedirectToRoute() method allows you to specify a route name and route values. It then redirects the control to that route. Suppose you have the default route in an MVC application defined in the Configure() method like this :

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

Now if you wish to redirect the control from Index() action to Privacy() action you would write this in the Index() :

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

As you can see, the RedirectToRoute() method accepts two parameter. The first parameter is the route name and the second parameter is an anonymous object that wraps the route values.

The RedirectToRoute() method returns RedirectToRouteResult object and sets the HTTP status code to 302 - Found.

RedirectToRoutePermanent(), RedirectToRoutePreserveMethod(), and RedirectToRoutePermanentPreserveMethod() methods

Just like the Redirect() method variations, the RedirectToRoute() also comes with the same set of variations. The RedirectToRoutePermanent() returns HTTP status code of 301. The RedirectToRoutePreserveMethod() preserves the request method (GET / POST) and sets the HTTP status code to 307. And RedirectToRoutePermanentPreserveMethod() preserves the HTTP method and also sets the HTTP status code to 308.

LocalRedirect() method

The LocalRedirect() method is similar to the Redirect() method but can be used to navigate only to the URLs local to your application. That means you can 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. You would use LocalRedirect() as shown below:

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

If you try to navigate to an external URL you will get an error. For example, if you try to navigate to example.com you will get an error.

LocalRedirectPermanent(), LocalRedirectPreserveMethod(), and LocalRedirectPermanentPreserveMethod() methods

Just like the Redirect() method variations, the LocalRedirect() also comes with the same set of variations. The LocalRedirectPermanent() returns HTTP status code of 301. The LocalRedirectPreserveMethod() preserves the request method (GET / POST) and sets the HTTP status code to 307. And LocalRedirectPermanentPreserveMethod() preserves the HTTP method and also sets the HTTP status code to 308.

That's it for now! Keep coding!!


Bipin Joshi is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a meditation teacher and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his ASP.NET online courses go here. More details about his Ajapa Japa and Shambhavi Mudra online course are available here.

Posted On : 17 January 2022







Advanced Ajapa Yoga Kriyas and Meditations for Software Developers : Tap the power of breath, mantra, mudra, and dhyana for improved focus, peace of mind, and blissful inner connection.