Redirect to different action without an redirect result (302)
You can Redirect a request to a different action without there being an intermediate redirect request the following way.
First you have the middleware look like this. Here we just edit the URL.
CustomRedirectMiddleware.cs
public class CustomRedirectMiddleware(RequestDelegate next)
{
private readonly RequestDelegate _next = next;
public async Task InvokeAsync(HttpContext context)
{
context.Request.Path = "/Home/Index";
await _next(context);
}
}
This can however only work before calling app.UseRouting since the routing middleware fills the IEndpoint feature and its request delegate.
Program.cs
app.UseRouting();
app.UseMiddleware<CustomRedirectMiddleware>();
Access Endpoint metadata in RedirectMiddleware
If for whatever reason you need any metadata from the endpoint before you can determine to redirect you must change the startup to this.
Program.cs
app.UseRouting();
app.UseMiddleware<CustomRedirectMiddleware>();
app.UseRouting();
This does by itself however not work. You also have set contexts.Endpoint to null, otherwise the second call to app.UseRouting will just use the results of the first one which will be a request delegate to the old URL.
CustomRedirectMiddleware.cs
public class CustomRedirectMiddleware(RequestDelegate next)
{
private readonly RequestDelegate _next = next;
public async Task InvokeAsync(HttpContext context)
{
// Retrieve the endpoint metadata from the current request.
var endpointFeature = context.Features.Get<IEndpointFeature>();
var endpoint = endpointFeature?.Endpoint;
// ignore static files
if (endpoint == null || endpoint.Metadata.GetMetadata<ShouldRedirectAttribute>() == null)
{
await _next(context);
return;
}
context.SetEndpoint(null); /* set it to null to make sure the second UseRouting middleware does its work */
// Rewrite the request path to /Home/Index
context.Request.Path = "/Home/Index";
await _next(context);
}
401or403(depending on whether it's authentication or authorization that fails), and if it's something else you probably don't want to do it in a middleware in the first place. Could you be more specific?