How to redirect a request in ASP.NET Core MVC

ASP.NET Core is a cross-platform, open source, lean, fast, and modular framework for building high-performance web applications. ASP.NET Core MVC applications enable you to redirect a request to a specified URL in several different ways. This article talks about how we can accomplish this with code examples wherever appropriate.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here. 

[ Also on InfoWorld: How to refactor God objects in C# ]

Create an ASP.NET Core MVC project in Visual Studio

First off, let’s create an ASP.NET Core project in Visual Studio 2019. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Create.
  8. In the “Create a New ASP.NET Core Web Application” window shown next, select .NET Core as the runtime and ASP.NET Core 3.1 (or later) from the drop-down list at the top.
  9. Select “Web Application (Model-View-Controller)” as the project template to create a new ASP.NET Core MVC application. 
  10. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  11. Ensure that Authentication is set to “No Authentication” as we won’t be using authentication either.
  12. Click Create.

Following these steps will create a new ASP.NET Core MVC project in Visual Studio 2019. We’ll use this project in the sections below to illustrate how we can redirect requests when working with action methods in ASP.NET Core 3.1.

Redirect action results in ASP.NET Core MVC

There are several types of action results in ASP.NET Core MVC such as RedirectResult, RedirectToActionResult, RedirectToRouteResult, and LocalRedirectResult. All of these classes extend the ActionResult class and the IActionResult and IKeepTempDataResult interfaces and return Found (Http Status Code 302), Moved Permanently (Http Status Code 301), Temporary Redirect (Http Status Code 307), or Permanent Redirect (Http Status Code 308).

We’ll examine how we can work with each of these in this section.

Copyright © 2020 IDG Communications, Inc.