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

ASP.NET 6 Web API中间件如何在服务端直接调用指定Action?

ASP.NET 6 Web API 服务端内部路由转发实现方案

要实现客户端请求/weatherforecast/Test时,服务端内部直接调用/weatherforecast/User对应的Action且不产生重定向,你需要确保中间件在路由匹配前修改请求上下文,并清除已有的路由相关状态,具体步骤如下:

1. 编写正确的转发中间件

修改请求路径后,必须清除路由匹配相关的上下文数据,让后续路由中间件重新匹配目标Action:

public class RequestResponseMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context)
    {
        // 匹配需要转发的请求路径
        if (context.Request.Path.Equals("/weatherforecast/Test", StringComparison.OrdinalIgnoreCase))
        {
            // 修改请求路径为目标Action的路径
            context.Request.Path = "/weatherforecast/User";

            // 清除已有的路由匹配相关数据,强制重新路由
            context.Features.Set<IEndpointFeature>(null);
            context.Features.Set<IRouteValuesFeature>(null);
            context.RouteData = new RouteData();
        }

        await _next(context);
    }
}

2. 正确注册中间件

必须将自定义中间件注册在UseRouting()之前,否则路由已经完成匹配,修改路径不会生效:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

// 自定义中间件要放在UseRouting前面
app.UseMiddleware<RequestResponseMiddleware>();

app.UseRouting();

app.UseAuthorization();

app.MapControllers();

app.Run();

关键说明

  • 之前方案失效的核心原因:如果中间件注册在UseRouting()之后,路由系统已经完成了初始匹配,此时修改路径无法触发重新路由;同时仅清空Endpoint和RouteValues不够,必须清除IEndpointFeature、IRouteValuesFeature和RouteData这些路由匹配的核心上下文数据。
  • 这种方式属于服务端内部路由转发,客户端不会感知到路径变化,也不会产生重定向请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:40:59