Redirect Results in ASP.NET Core MVC

Redirect Results in ASP.NET Core MVC

In this article, I will discuss the Redirect Results in ASP.NET Core MVC Web Applications with Examples. Please read our previous article about the File Result in ASP.NET Core MVC Applications.

Redirect Results in ASP.NET Core MVC

Redirect Results in ASP.NET Core MVC are a type of action result that instructs the client’s browser to navigate to a different URL (outside the application) or action within the application. There are three main types of Redirect Results in ASP.NET Core MVC:

  • RedirectResult: Redirects the client to another URL. It is useful in scenarios where you want to redirect the user to an external URL. 
  • RedirectToRoute: This represents a response that redirects to a specific route configured in your application.
  • RedirectToActionResult: Represents a response that redirects to a specific action and controller within the application.

Redirect Results are commonly used for scenarios like Post-Redirect-Get (PRG) Patterns, where a form submission is followed by a redirection to prevent duplicate submissions. They are also used to implement Authentication Flows, Process Data, and handle various user interactions in your application. By using Redirect Results, we can implement proper navigation within the application or to external resources.

Redirect Result in ASP.NET Core MVC

In ASP.NET Core MVC, the Redirect Result is an action result that instructs the client’s browser to redirect to a different URL. You can use it when you want to redirect users to a different location, whether it’s within the same application or to an external URL. This can be useful for scenarios like handling form submissions, processing data, and then redirecting the user to a different page.

If you go to the definition of RedirectResult, you will see that it is a class with 3 constructors, a few properties, and one overriding method, as shown in the image below.

Redirect Results in ASP in ASP.NET Core MVC Web Application with Examples

How Does the ExecuteResultAsync Method of RedirectResult class Work in ASP.NET Core MVC?

The ExecuteResultAsync method in the RedirectResult class is responsible for executing the result of an action method that returns a RedirectResult. Here is how the ExecuteResultAsync method works within the RedirectResult class:

  • Setting Redirect URL: Before returning the RedirectResult from the action method, we need to set the URL property to specify the URL where the client should be redirected.
  • Execution: When the action method returns a RedirectResult object, the ASP.NET Core MVC framework handles it by calling the ExecuteResultAsync method of that RedirectResult object.
  • Redirecting: Within the ExecuteResultAsync method, the ASP.NET Core MVC framework generates an HTTP redirect response (status code 302) with the specified URL in the Location header. This instructs the client’s browser to navigate to the specified URL.
Example to Understand Redirect Result in ASP.NET Core MVC

Let us understand this with an example. Suppose you want to redirect to a specific URL. This method takes the URL to redirect. For example, if we want to redirect to the URL https://dotnettutorials.net, we need to use the Redirect method, as shown below.

using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public RedirectResult Index()
        {
            return new RedirectResult("https://dotnettutorials.net");
        }
    }
}
Using RedirectResult Helper Method:

Alternatively, you can use the Redirect helper method provided by the Controller class to create a RedirectResult. This method simplifies the creation of redirect results.

using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public RedirectResult Index()
        {
            return Redirect("https://dotnettutorials.net");
        }
    }
}

Note: Don’t use the other overloaded constructor versions, or you will make your redirection permanent.

RedirectToRouteResult in ASP.NET Core MVC

In ASP.NET Core MVC, RedirectToRouteResult is an action result that redirects the client to a specified route. It allows you to redirect the user to a different action within the same controller or to an action in a different controller. Routes in ASP.NET Core MVC define how URLs are mapped to controller actions. By using RedirectToRouteResult, you can take advantage of these route definitions to dynamically redirect users based on the route configuration.

How Does ExecuteResultAsync Method of RedirectToRouteResult class Works in ASP.NET Core MVC?

The ExecuteResultAsync method in the RedirectToRouteResult class is responsible for executing the result of an action method that returns a redirect to a route result. Here is how the ExecuteResultAsync method works within the RedirectToRouteResult class:

  • Setting Route Values: Before returning the RedirectToRouteResult from the action method, we need to set the RouteValues property to specify the route to which the client should be redirected. The route values typically include the controller, action, and any additional parameters required by the route.
  • Execution: When the action method returns a RedirectToRouteResult object, the ASP.NET Core MVC framework handles it by calling the ExecuteResultAsync method of that RedirectToRouteResult object.
  • Redirecting: Within the ExecuteResultAsync method, the ASP.NET Core MVC framework generates an HTTP redirect response (status code 302) with the URL constructed based on the specified route values. This instructs the client’s browser to navigate to the specified route.
Example to Understand RedirectToRouteResult in ASP.NET Core MVC

Let us understand RedirectToRouteResult with some examples. First, we need to create a Route with the name AboutRoute within our Program.cs class file, which should execute the About Action method of the Home Controller. So, modify the Home Controller as follows. Here, you can see first, we have registered the AboutRoute and then the default Route.

using Microsoft.AspNetCore.Http.Json;
using Microsoft.AspNetCore.Mvc;
using System;

namespace ActionResultInASPNETCoreMVC
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllersWithViews();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            //URL Pattern: about
            app.MapControllerRoute(
                name: "AboutRoute",
                pattern: "about",
                defaults: new { controller = "Home", action = "About" }
            );

            //URL Pattern: Controller/Action
            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            app.Run();
        }
    }
}
Modifying the Home Controller:

Next, modify the Home Controller as follows. Here, you can see within the Index action method, we redirect to the AboutRoute using the RedirectToRoute method.

using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public RedirectToRouteResult Index()
        {
            // Perform some logic

            // Redirect to a different route
            // You need to specify the Route Name, not the Route Pattern
            return RedirectToRoute("AboutRoute");
        }

        public string About()
        {
            return "Hello and Welcome to Dot Net Tutorials";
        }
    }
}

Remember that RedirectToRouteResult allows you to define more complex redirection scenarios involving different controllers, actions, and route values. It is useful when abstracting the route logic from the specific controller and action names. In the below example, we are directing the user to the AboutRoute Route with some data.

using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public RedirectToRouteResult Index()
        {
            // Perform some logic

            // Redirect to a different route
            // You need to specify the Route Name, not the Route Pattern
            return RedirectToRoute("AboutRoute", new { name = "Index" });
        }

        public string About(string name)
        {
            return "Hello and Welcome to Dot Net Tutorials " + name;
        }
    }
}

The RedirectToRouteResult is also used whenever we need to move from one action method to another within the same or different controller in an ASP.NET Core MVC Application. For example, in the below code, we redirect to the Home Controller’s About action method from the Home Controller’s Index action method.

using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public RedirectToRouteResult Index()
        {
            // Perform some logic

            // Redirect to a different route
            // You need to specify the Route Name, not the Route Pattern
            //return RedirectToRoute("AboutRoute", new { name = "Index" });

            return RedirectToRoute(new { controller = "Home", action = "About", name="Index" });
        }

        public string About(string name)
        {
            return "Hello and Welcome to Dot Net Tutorials " + name;
        }
    }
}

Note: Specifying the controller’s name is optional if you redirect to an action method within the same controller, but navigating to a different controller is mandatory.

RedirectToActionResult in ASP.NET Core MVC

In ASP.NET Core MVC, RedirectToActionResult is an action result that redirects the client to another action within the same controller or a different controller. It allows you to redirect users to a different action based on the action name and controller name. Specifying the controller’s name is optional if you redirect to an action method within the same controller, but navigating to a different controller is mandatory.

How Does the ExecuteResultAsync Method of RedirectToActionResult class Work in ASP.NET Core MVC?

The ExecuteResultAsync method in the RedirectToActionResult class is responsible for executing the result of an action method that returns a redirect to an action result. Here is how the ExecuteResultAsync method works within the RedirectToActionResult class:

  • Setting Action and Controller Names: Before returning the RedirectToActionResult from the action method, we need to set the ActionName, ControllerName, and optionally RouteValues properties to specify the action and controller to which the client should be redirected.
  • Execution: When the action method returns a RedirectToActionResult object, the ASP.NET Core MVC framework handles it by calling the ExecuteResultAsync method of that RedirectToActionResult object.
  • Redirecting: Within the ExecuteResultAsync method, the ASP.NET Core MVC framework generates an HTTP redirect response (status code 302) with the URL constructed based on the specified action, controller, and route values. This instructs the client’s browser to navigate to the specified action.
Example to Understand RedirectToActionResult in ASP.NET Core MVC

Let us understand RedirectToActionResult with some examples. So, please modify the Home Controller as follows:

using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public RedirectToActionResult Index()
        {
            // Perform Some Logic

            // Redirect to a different action within the same controller
            // Specifying the Controller name is Optional
             return RedirectToAction("AboutUs", "Home" );
           //  return RedirectToAction("AboutUs");
        }

        public string AboutUs(string name)
        {
            return "Hello and Welcome to Dot Net Tutorials " + name;
        }
    }
}

In the above example, when the Index action is invoked, it performs some logic (which you can replace with your logic). Then, it uses RedirectToAction to redirect the user to the AboutUs action method within the same controller. You can also use additional overloads of RedirectToAction to provide route values and query parameters:

using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public RedirectToActionResult Index()
        {
            // Perform Some Logic

            // Redirect to the About action with a Route Parameter
            //return RedirectToAction("About", new { id = 123 });

            // Redirect to the About action with a Query String Parameter
            return RedirectToAction("About", "Home", new { id = 123, name = "Index" });
        }

        public string About(int id, string name)
        {
            return $"Hello and Welcome to Dot Net Tutorials, Id{id}, Name:{name} ";
        }
    }
}
Differences Between RedirectResult, RedirectToRoute Result, and RedirectToActionResult in ASP.NET Core MVC

In ASP.NET Core MVC, RedirectResult, RedirectToRouteResult, and RedirectToActionResult are all used to perform HTTP redirections. Still, they differ in terms of how they handle the redirection. The following are the differences between these three classes:

RedirectResult:
  • Represents an HTTP redirection response to an absolute URL. 
  • You specify the URL you want to redirect to as a parameter.
  • Typically used for external redirects or redirects to URLs that are not handled by your application’s routing system.
  • Example: return Redirect(“https://www.dotnettutorials.net”);
RedirectToRouteResult:
  • Represents an HTTP redirection response to a named route defined in your application’s routing configuration.
  • You specify the name of the route you want to redirect to.
  • Used to redirect to different controllers and actions while providing route values and parameters.
  • Example: return RedirectToRoute(“AboutRoute”);
RedirectToActionResult:
  • Represents an HTTP redirection response to a specific action within a specific controller.
  • You specify the action and, optionally, the controller, along with any route values, query parameters, and fragment identifiers.
  • It offers the highest level of abstraction by allowing you to specify the action and controller by name.
  • Example: return RedirectToAction(“About”, new { id = 123 });

In the next article, I will discuss the StatusResult in ASP.NET Core MVC Application. In this article, I explain Redirect Results in ASP.NET Core MVC Application with Examples. I hope you enjoy this Redirect Results in ASP.NET Core MVC Application article.

Leave a Reply

Your email address will not be published. Required fields are marked *