You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 8:请求不存在的控制器时重定向至旧应用的实现

在.NET 8中实现未迁移请求自动重定向到旧应用

可以通过以下两种灵活方式在应用内实现需求,核心逻辑是捕获未匹配到已迁移资源的404请求,将其重定向到旧应用对应地址:

方法一:全局中间件拦截(推荐)

这种方式能覆盖所有请求类型,适配MVC、Web API等场景:

  1. 先在appsettings.json配置旧应用基础地址:
"OldAppConfig": {
  "BaseUrl": "https://oldhostname.example.com"
}
  1. 编写自定义中间件类:
public class RedirectUnmigratedRequestsMiddleware
{
    private readonly RequestDelegate _next;
    private readonly string _oldAppBaseUrl;

    public RedirectUnmigratedRequestsMiddleware(RequestDelegate next, IConfiguration config)
    {
        _next = next;
        _oldAppBaseUrl = config.GetValue<string>("OldAppConfig:BaseUrl") ?? string.Empty;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // 先让请求正常流转,匹配已迁移的控制器/方法
        await _next(context);

        // 若返回404,说明资源未迁移,执行重定向
        if (context.Response.StatusCode == StatusCodes.Status404NotFound && !string.IsNullOrEmpty(_oldAppBaseUrl))
        {
            // 拼接旧应用完整地址:旧域名+当前请求路径+查询参数
            var targetUrl = $"{_oldAppBaseUrl}{context.Request.Path}{context.Request.QueryString}";
            
            // 用301永久重定向(若后续可能迁移该路径,可改用302临时重定向)
            context.Response.Redirect(targetUrl, permanent: true);
        }
    }
}
  1. 在Program.cs中注册中间件(注意要放在路由中间件之前):
var builder = WebApplication.CreateBuilder(args);

// 注册其他服务...

var app = builder.Build();

// 添加自定义重定向中间件
app.UseMiddleware<RedirectUnmigratedRequestsMiddleware>();

// 后续添加路由、端点等中间件
app.UseRouting();
app.MapControllers();

app.Run();

方法二:MVC全局结果过滤器

如果应用以MVC控制器为主,可以用过滤器精准拦截控制器返回的404结果:

  1. 创建过滤器类:
public class RedirectUnmigratedFilter : IAsyncResultFilter
{
    private readonly IConfiguration _config;

    public RedirectUnmigratedFilter(IConfiguration config)
    {
        _config = config;
    }

    public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
        // 判断是否为控制器返回的404结果
        if (context.Result is NotFoundResult || context.Result is NotFoundObjectResult)
        {
            var oldAppBaseUrl = _config.GetValue<string>("OldAppConfig:BaseUrl");
            if (!string.IsNullOrEmpty(oldAppBaseUrl))
            {
                var targetUrl = $"{oldAppBaseUrl}{context.HttpContext.Request.Path}{context.HttpContext.Request.QueryString}";
                context.Result = new RedirectResult(targetUrl, permanent: true);
            }
        }

        await next();
    }
}
  1. 在Program.cs中注册过滤器:
builder.Services.AddControllers(options =>
{
    options.Filters.Add<RedirectUnmigratedFilter>();
});

额外提醒

  • 如果有业务逻辑刻意返回的404(非未迁移导致),需要添加排除规则,比如在中间件/过滤器里判断请求路径是否在白名单中,避免误重定向。
  • 测试阶段建议用302临时重定向,确认逻辑无误后再切换为301永久重定向。

内容的提问来源于stack exchange,提问作者JoeMcAlly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 19:55:00