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

.NET 7中AddEndpointFilter启动时抛出InvalidOperationException异常

.NET 7 Minimal API使用AddEndpointFilter启动时抛出InvalidOperationException异常

环境信息

  • .NET 7(版本7.0.102)
  • Microsoft Visual Studio Professional 2022(64位,版本17.6.3)

异常详情

调试启动ASP.NET Core Minimal APIs项目时,调用AddEndpointFilter<OperationCancelledFilter>会抛出以下InvalidOperationException异常:

System.InvalidOperationException
HResult=0x80131509
Message=A suitable constructor for type 'WebApplication3.OperationCancelledFilter' could not be located. Ensure the type is concrete and all parameters of a public constructor are either registered as services or passed as arguments. Also ensure no extraneous arguments are provided.
Source=Microsoft.Extensions.DependencyInjection.Abstractions
StackTrace:
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.FindApplicableConstructor(Type instanceType, Type[] argumentTypes, ConstructorInfo& matchingConstructor, Nullable`1[]& matchingParameterMap) in /_/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ActivatorUtilities.cs:line 216
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateFactory(Type instanceType, Type[] argumentTypes) in /_/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ActivatorUtilities.cs:line 97
at Microsoft.AspNetCore.Http.EndpointFilterExtensions.AddEndpointFilter[TBuilder,TFilterType](TBuilder builder)

现象说明

点击调试器的“继续”按钮后,程序可正常启动,过滤器也能正常触发断点,但启动阶段始终存在该未处理异常。

触发异常的自定义过滤器代码

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app
    .MapGet("/", () => "Hello World!")
    .AddEndpointFilter<OperationCancelledFilter>();

app.Run();

class OperationCancelledFilter : IEndpointFilter
{
    private readonly ILogger<OperationCancelledFilter> _logger;

    public OperationCancelledFilter(
        ILogger<OperationCancelledFilter> logger
        )
    {
        _logger = logger;
    }

    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {
        try
        {
            return await next(context);
        }
        catch (OperationCanceledException ex)
        {
            _logger.LogDebug(ex, "Request was cancelled");

            return Results.StatusCode(499);
        }
    }
}

无异常的内联过滤器写法

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app
    .MapGet("/", () => "Hello World!")
    .AddEndpointFilter(async (context, next) =>
    {
        var logger = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("program");

        try
        {
            return await next(context);
        }
        catch (OperationCanceledException ex)
        {
            logger.LogDebug(ex, "Request was cancelled");

            return Results.StatusCode(499);
        }
    });

app.Run();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:28:26