Redirect a request in ASP.NET Core

Redirecting a request means returning a response with redirect status code (3xx) and a redirect URL in the Location header. The client uses this info to follow the redirect (which means making a request to the redirect URL). You can redirect by using a helper method (from ControllerBase) or returning a RedirectResult. I’ll show several examples.

Here’s an example of doing a 301 (temporary) redirect to a local URL by using the Redirect() helper method:

/* 
	Status code: 301 (temporary)
	Location: /weather
*/

return Redirect("/weather");

return new RedirectResult("/weather");

Code language: C# (cs)

Here’s an example of redirecting to an external site by specifying a full URL:

/*
	Status code: 301 (temporary)
	Location: https://microsoft.com
*/

return Redirect("https://microsoft.com");

return new RedirectResult("https://microsoft.com");
Code language: C# (cs)

By default, Redirect() does a 301 (temporary) redirect. You can use RedirectPermanent() to do a 302 (permanent) redirect:

/* 
	Status code: 302 (permanent)
	Location: /weather
*/
 
return RedirectPermanent("/weather"); 

return new RedirectResult("/weather", permanent: true);
Code language: C# (cs)

You can do a preserve method redirect (308 or 307) with RedirectPermanentPreserveMethod():

/* 
	Status code: 308 (permanent + preserve method)
	Location: /weather
*/
 
return RedirectPermanentPreserveMethod("/weather");

return new RedirectResult("/weather", permanent: true, preserveMethod: true);

Code language: C# (cs)

Note: Preserve Method means the client should follow the redirect using original HTTP method (GET/POST).

There are special redirect helper methods to help you build the redirect URL. For example, you can use RedirectToAction() to redirect to an action method. It builds the action method’s URL for you.

/*
	If the action is in this controller

	Status code: 302 (permanent)
	Location: /weatherforecast/all

*/

return RedirectToAction(actionName: nameof(GetAll));

/*
	If the action is in a different controller 
 
	Status code: 302 (permanent)
	Location: /movie/all
 
*/
 
return RedirectToAction(actionName: nameof(MovieController.GetAll), controllerName: "Movie");
Code language: C# (cs)

I’ll now show other redirection scenarios.

Redirect from middleware

Here’s an example of adding a middleware class that handles redirects:

public class RedirectMiddleware
{
	private readonly RequestDelegate NextMiddleware;
	public RedirectMiddleware(RequestDelegate nextMiddleware)
	{
		NextMiddleware = nextMiddleware;
	}
	public async Task InvokeAsync(HttpContext context)
	{
		//1 - Check the request path for redirect conditions
		if (context.Request.Path == "/content/getallmovies/")
		{ 
			//2 - Redirect
			context.Response.Redirect("/movies/", permanent: true, preserveMethod: true);
			return;
		}

		//3 - Otherwise call the next middleware
		await NextMiddleware(context);
	}
}
Code language: C# (cs)

You can check the request path for any redirect conditions you want:

  • The path string matches a specific path you’re looking for (as shown above).
  • The path string starts or end with a specific value.
  • The path string contains a specific value anywhere in the string.

To use this, add it with app.UseMiddleware() in the initialization code:

var app = builder.Build();

//rest of init

app.UseHttpsRedirection();
app.UseMiddleware<RedirectMiddleware>(); //Add after UseHttpsRedirection()

//rest of init

app.Run();
Code language: C# (cs)

Note: Before .NET 6, do this in Startup.Configure().

HTTP to HTTPS redirects

Use the built-in HttpsRedirectionMiddleware for handling HTTP to HTTPS redirects. If your code isn’t already using this, add app.UseHttpsRedirection() to the initialization code (and app.UseHsts() if the client is a browser).

By default, it does a 307 redirect (temporary, preserve method). You can configure the redirect status code you want to use with builder.Services.AddHttpsRedirection().

Here’s an example of adding and configuring HTTPS redirection:

var builder = WebApplication.CreateBuilder(args);

//Configure it if you want
builder.Services.AddHttpsRedirection(options =>
{
    options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
});

//rest of init

var app = builder.Build();

//rest of init 

app.UseHttpsRedirection();

//rest of init

app.Run();
Code language: C# (cs)

Leave a Comment