我想对所有asp.net核心最小API端点应用过滤器.

我想这样做的原因是对端点的返回值进行后处理.类似于这样的:

    public class GlobalFilter : IEndpointFilter
    {
        private ILogger _logger;

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

        public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext invocationContext, EndpointFilterDelegate next)
        {
            try
            {
                var res = await next(invocationContext);
                var result = res as Result;
                if(result is not null)
                {
                    // Here, access the `result` members and modify the return value accordingly...
                }

                return Results.Problem();
            }
            catch (Exception ex)
            {
                return Results.Problem(ex.ToString());
            }
        }
    }
            app
                .MapPost("api/document/getById", async ([FromBody] GetDocumentRequest request) =>
                {
                    var result = ...result-producing call...;
                    return result;
                })
                .AddEndpointFilter<GlobalFilter>() // Manually assigning the filter.
                ...
                ...;

这似乎有效,但我必须记住每次手动设置过滤器. 是否有方法将此过滤器自动应用于所有端点?

或者,是否可以用另一种方法实现同样的事情?据我所知,使用中间件不允许您判断端点返回值,而只能处理引发的异常.

推荐答案

您可以将过滤器应用于MapGroupMapGroup可以指向所有最小端点.

示例:

public static class GroupEndPointsExt
{
    public static RouteGroupBuilder MapMinimalApi(this RouteGroupBuilder group)
    {
      group.MapPost("document/getById", async ([FromBody] GetDocumentRequest request) =>
      {
                    var result = ...result-producing call...;
                    return result;
       });
//add other minimal endpoints here where global filter will apply
        return group;
    }
}

然后在您的Program.cs中,将GlobalFilter应用于包含方法MapMinimalApi中定义的所有最小端点的路由组

app.MapGroup("api").MapMinimalApi().AddEndpointFilter<GlobalFilter>();
//Global filter will apply to all endpoints in this route group
//all endpoints in this route group will use path prefixed with api

Csharp相关问答推荐

在包含空项的列表上使用具有断言T的摘要表

Unity如何在PlayerPrefs中保存数据?

使用yaml将Azure函数代码部署到FunctionApp插槽时出现问题(zip未找到)

如何循环遍历XML文档 node 以使用XSLT存储值

.NET 8 Web-API返回空列表

Blazor Foreach仅渲染最后一种 colored颜色

可为空的泛型属性

在具有主构造函数的类中初始化属性时出现警告

mocking对象的引发事件并作为用于调用方法的参数对象传递到那里

MigraDoc文档

如何注册类使用多级继承与接口

Docker Container中的HttpRequest后地址不可用

try 使用C#ASP.NET收集WMI信息时访问被拒绝,但在PowerShell中工作

HttpClient 415不支持的媒体类型错误

C#使用TextFieldParser读取.csv,但无法使用";0";替换创建的列表空条目

在C#中,将两个哈希集连接在一起的时间复杂度是多少?

链接到字典字符串.拆分为(.Key,.Value)

多个选项卡上的MudForm验证

WPF如何获取有关从一个视图模型更改另一个视图模型的信息

外部应用&&的LINQ;左外部连接&类似于PostgreSQL的查询