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

ASP.NET Core中如何为/GetUser请求映射自定义中间件

问题解决:ASP.NET Core 中通过指定路径触发自定义中间件

你的核心问题是对app.Map的用法理解有误,Map需要传入一个配置分支中间件管道的委托,而非直接传递中间件调用结果,且不能使用WebApplicationBuilder实例来调用中间件扩展方法,应该用构建后的WebApplication(即app)或其分支。

正确的Program.cs配置

修改Program.cs中的代码,将Map的用法调整为分支配置:

var builder = WebApplication.CreateBuilder(args);

// 添加Razor Pages服务
builder.Services.AddRazorPages();

var app = builder.Build();

// 为/GetUser路径配置专属中间件管道
app.Map("/GetUser", appBranch => 
{
    // 在分支管道中启用GetUser中间件
    appBranch.UseGetUser();
});

// 保留必要的全局中间件(根据你的项目需求调整)
app.UseRouting();
app.UseAuthorization();

app.MapRazorPages();

app.Run();

中间件代码优化建议

你的GetUser中间件作为终端处理程序(不调用后续中间件),当前写法没问题,但异常处理部分需要补充响应输出,否则异常发生时客户端无法收到错误信息:

public class GetUser
{
    // 终端中间件无需存储next,构造函数可以保留(符合中间件约定)
    public GetUser(RequestDelegate next)
    {
    }

    public async Task Invoke(HttpContext context)
    {
        string response = string.Empty;

        try
        {
            response = GenerateResponse(context);

            context.Response.ContentType = "text/plain";
            context.Response.StatusCode = StatusCodes.Status200OK;

            await context.Response.WriteAsync(response);
        }
        catch (System.Exception ex)
        {
            response = ex.Message;
            // 异常时设置500状态码并输出错误信息
            context.Response.ContentType = "text/plain";
            context.Response.StatusCode = StatusCodes.Status500InternalServerError;
            await context.Response.WriteAsync(response);
        }
    }

    public string GenerateResponse(HttpContext context)
    {
        return "a response";
    }
}

public static class GetUserExtension
{
    public static IApplicationBuilder UseGetUser(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<GetUser>();
    }
}

关键说明

  • app.Map("/GetUser", ...)会为所有以/GetUser开头的请求创建一个独立的中间件分支,仅该分支下的中间件会处理这些请求。
  • appBranch是IApplicationBuilder类型的实例,因此可以直接调用你的UseGetUser扩展方法。
  • 确保在配置分支中间件后,保留全局必要的中间件(如路由、授权),避免影响其他页面的正常运行。

内容的提问来源于stack exchange,提问作者Paul S Chapman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:05:21