How To Redirect ASP.NET MVC Core Request

There are often requests that need to be redirected temporarily or permanently from the current request to other requests. ASP.NET MVC Core RedirectResult, RedirectToActionResult, RedirectToRouteResult, LocalRedirectResult can be used for redirection.

The ASP.NET Core MVC Action Method returns different type of Action Result like Content, Redirect, File, HTTP Status Code. Each Redirect Result has different way of redirection and execution. This redirection can be absolute or relative URL.

All following return statements redirect the client to the Index action method of the Product Controller with some difference in execution.

return Redirect("/Product/Index");
return RedirectPermanent("/Product/Index");
return RedirectPermanentPreserveMethod("/Product/Index");
return RedirectPreserveMethod("/Product/Index"); 

Each redirection result explained in detail.

  1. RedirectResult

    The RedirectResult redirects client to other relative or absolute URL. This Redirection can be permanent or temporary. Following code returns HTTP Status code 302 (Temporarily moved)

    RedirectResult is defined in Microsoft.AspNetCore.Mvc namespace. The syntax for this resultset is RedirectResult(string url, bool permanent, bool preserveMethod).

    The following code redirects the current Index request to the Product controller's new index Action method. This will be redirected as permanent with status code 301(Moved Permanently) and preserves the current HTTP request type, so if the current request type is GET then redirection will happen with GET request type.

    public RedirectResult Index()
    {
        return new RedirectResult(url:"/Product/NewIndex", permanent: true, preserveMethod: true);
    }
    
  2. RedirectPermanent

    This method is similar to Redirect RedirectPermanent redirects current requests to new locations permanently with status code 301. This indicates the requested resource is a permanent new location.

    This method is very useful for Search Engine Optimization when you are migrating your website to a new domain or new structure.

    public RedirectResult RedirectPermanentTest()
    {
        RedirectResult result = RedirectPermanent("https://geeksarray.com");
        return result;
    }
    

    This code executes and returns as shown in following the image. This sets permanent as true.

    ASP.NET Core Redirect Permanent Test

  3. RedirectPreserveMethod

    RedirectResult can also return RedirectPreserveMethod to temporary redirect(HTTP Status code 307) to new location. However, this method preserves the request method. For example, if your current request is HTTPGet then the redirection will be requested with the HTTPGet method.

    This creates the RedirectResult object by setting Permanent as false and PreserveMethod as true. This method accepts a string parameter that needs to be a valid URL.

    public RedirectResult RedirectResultTest()
    {
        return RedirectPreserveMethod("https://geeksarray.com");
    }
    
  4. RedirectPermanentPreserveMethod

    The RedirectPermanentPreserveMethod executes in a similar way as RedirectPreserveMethod, the only difference is, this returns HTTP Status Code 308 Redirect Permanent.

    The following code redirects the current requests by preserving the current request type(GET or POST) from localhost to geeksarray.com permanently.

    public RedirectResult RedirectResultTest()
    {            
        return RedirectPermanentPreserveMethod("https://geeksarray.com");
    }
    

    ASP.NET Core MVC RedirectPermanentPreserveMethod

  5. LocalRedirectResult

    This action gives a response similar to RedirectResult with one difference and that is you can redirect to only URLs that are internal to the application. This prevents Open redirect attacks. If you provide any external URL outside of the website then this method throws InvalidOperationException.

    The LocalRedirect method returns the LocalRedirectResult object and sets the HTTP status code to 302 - Temporarily moved.

    public LocalRedirectResult LocalRedirectResultTest()
    {
        return LocalRedirect("/home/ShowEmployee");
    }
    

    The variations which we have seen with RedirectResult are also available with LocalRedirectResult. The LocalRedirectResult can return any from LocalRedirectPermanent, LocalRedirectPreserveMethod, and LocalRedirectPermanentPreserveMethod. The execution way for each of these methods is explained in the previous step.

  6. RedirectToActionResult

    This action result redirects clients to specify a specific Action method, Controller, Area of the same application. You can specify controller name, Area Name, and Index name. For detailed description about Area visit - How to use ASP.NET Core MVC Area

    If you don't specify Area Name then current Area is used to search the controller. If you don't use the controller name then the Action Method of the current controller is executed. If you don't specify Action Name then the default action method is executed.

    The following code shows how to use RedirectToActionResult by using different action methods from different Controllers or Areas or ActionMethod from the current controller.

    public RedirectToActionResult RedirectToActionResultTest()
    {
        //Redirects to Index Action Method from HomeController
        return RedirectToAction(actionName: "Index", controllerName: "Home");
    
        //Redirects to Index Action Method from the current Controller
        return RedirectToAction(actionName: "Index");
    
        //Redirects to Index Action Method from ProdutctController of Product Area
        return RedirectToAction(actionName: "Index", controllerName: "Product", 
            new { area = "Product" });
    }
    
  7. RedirectToRouteResult

    ASP.NET MVC Routing creates map between URL templates with controllers and actions.

    This action result redirects the client to a specific route. This action takes a route name, route value and redirects us to that route with the route values provided. The route name used here must be declared in Startup.cs.

    Defining route in ASP.NET MVC Core.

    app.UseEndpoints(ep =>
    {   
    
        ep.MapControllerRoute(
            name: "areaRoute",
            pattern: "{area:exists}/{controller}/{action}"
        );
    
        ep.MapControllerRoute(
            name: "default",
            pattern: "{controller}/{action}/{id?}",
            defaults: new { controller = "Home", action = "Index" });                    
        }
    );   
    

    Using pre-defined routes to redirect current request to new location.

    public RedirectToRouteResult RedirectToRouteResultTest()
    {
        //Redirect using route name
        return RedirectToRoute("default");
    
        //Redirect using Route Value
        var routeValue = new RouteValueDictionary(new { action = "Index", 
                controller = "Home", area="Product" });
        return RedirectToRoute(routeValue);
    }
    

    The RedirectToRouteResult can also return RedirectToRoutePermanent, RedirectToRoutePreserveMethod, and RedirectToRoutePermanentPreserveMethod.

Source code on Git hub Source Code on Github

Speak your mind
Please login to post your comment!