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

ASP.NET 6中间件路由重定向致接口重复调用问题排查

问题根源分析
  1. 中间件未终止原请求管道执行:调用context.Response.Redirect后没有立即返回,导致后续中间件和控制器逻辑继续执行,所以Test方法被调用1次;同时浏览器收到重定向指令后发起新请求。
  2. 重定向逻辑未过滤目标请求:如果中间件没有判断当前请求是否已经是重定向目标(/weatherforecast/User),会导致目标请求被重复重定向,浏览器多次发起请求直到终止,进而UserInfo方法被多次调用。
  3. 路由映射配置拼写错误:JSON配置里的Controllor(应为Controller)、Metods(应为Methods)拼写错误,可能导致路由映射逻辑无法正确解析,触发异常重定向。
修复方案

1. 修正中间件逻辑,避免循环重定向与管道泄漏

在重定向后终止请求管道,同时添加目标请求过滤,防止循环重定向:

public class RequestResponseMiddleware
{
    private readonly RequestDelegate _next;

    public RequestResponseMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        // 跳过目标请求,避免循环重定向
        if (context.Request.Path.StartsWithSegments("/weatherforecast/User"))
        {
            await _next(context);
            return;
        }

        // 匹配需要重定向的路径
        if (context.Request.Path.StartsWithSegments("/weatherforecast/Test"))
        {
            // 使用307临时重定向(保持原请求方法),减少浏览器重复请求概率
            context.Response.StatusCode = StatusCodes.Status307TemporaryRedirect;
            // 携带原请求的QueryString
            context.Response.Headers.Location = $"/weatherforecast/User{context.Request.QueryString}";
            return; // 终止管道,不再执行原控制器方法
        }

        await _next(context);
    }
}

2. 修正路由映射配置的拼写错误

修正JSON中的拼写问题,确保配置能被正确解析:

{
    "Routes":[
        {
            "Controller": "WeatherForecast",
            "Methods":[
                {
                    "Test": "User" 
                },
                {
                    "Weather": "Weather"
                }
            ]
        }
    ]
}

3. 确保路由与控制器方法正确绑定

在控制器中添加路由特性,保证/weatherforecast/User能映射到UserInfo方法:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet("Test")]
    public IActionResult Test()
    {
        return Ok("Test");
    }

    [HttpGet("User")]
    public IActionResult UserInfo()
    {
        return Ok("UserInfo");
    }
}

4. 调整中间件注册顺序

确保自定义中间件注册在路由中间件之前,让重定向逻辑优先执行:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

// 自定义中间件必须在UseRouting之前注册
app.UseMiddleware<RequestResponseMiddleware>();

app.UseRouting();
app.UseAuthorization();
app.MapControllers();

app.Run();
验证效果

访问https://localhost:7290/weatherforecast/Test?t=1675343945003&m=&k=sdf时,浏览器会直接重定向到/weatherforecast/User,Test方法不会被调用,UserInfo方法仅执行1次。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:25:21