如何在.NET Core中间件的UseEndpoints之前检查路由是否有效?

huangapple go评论64阅读模式
英文:

How can I check if a route is valid in a .NET Core middleware before UseEndpoints does?

问题

我正在使用.NET Core 3.1创建一个Web API。

我的API控制器正在使用以下方式映射:

app.UseEndpoints(endpoints => endpoints.MapControllers());

是否有一种方法可以在路由匹配之后但在实际控制器操作执行之前执行某个操作?

我处于需要在应用程序逻辑执行之前在数据库中创建一个实体的情况下。

我最初考虑了自定义中间件,但后来发现如果将中间件放在 app.UseEndpoints 之前,它会对所有请求都触发(会创建很多虚拟实体),甚至那些不进行路由的请求也会触发。

如果我将其放在 app.UseEndpoints 之后,那就太晚了,因为应用程序代码已经执行。

在在 app.UseEndpoints 之前运行的中间件中管理路由的白名单是一个想法,但会很麻烦。

所以,是否有一种方法可以连接到终点路由,或者框架中是否有一个API可以让我在路由有效之前“预先”确定路由是否有效?

英文:

I am using .NET Core 3.1, creating a web api.

My API Controllers are being mapped with the following:

app.UseEndpoints(endpoints => endpoints.MapControllers());

Is there a way that I can perform an action only if a route matches, but before the actual controller action is executed?

I'm in a situation where I need to create an entity in the database before the application logic is executed.

I initially considered a custom middleware, but only to realise that if I place the middleware before app.UseEndpoints it would fire for any and all requests (lots of dummy entities would be created), even those that don't route.

If I place it after app.UseEndpoints it's too late as the application code will have already executed.

Managing a white list of routes in a middleware that runs before app.UseEndpoints was a thought, but would be a maintenance hassle.

So is there a way to hook into the endpoint routing, or an API in the framework that can let me "preemptively" determine if a route is valid?

答案1

得分: 5

UseRouting方法负责确定哪个端点将会运行。如果找到匹配项,它会设置当前HttpContextEndpoint。您可以在中间件组件中使用HttpContext.GetEndpoint来访问它。以下是使用这种方法的示例:

app.UseRouting();

app.Use(async (ctx, next) =>
{
    // 使用 Microsoft.AspNetCore.Http;
    var endpoint = ctx.GetEndpoint();

    if (endpoint != null)
    {
        // 已匹配到一个端点。
        // ...
    }

    await next();
});

app.UseEndpoints(endpoints => endpoints.MapControllers());
英文:

The call to UseRouting does the job of figuring out which endpoint is going to run. If a match is found, it sets the Endpoint for the current HttpContext. This is available inside a middleware component using HttpContext.GetEndpoint. Here's an example that uses this approach:

app.UseRouting();

app.Use(async (ctx, next) =>
{
    // using Microsoft.AspNetCore.Http;
    var endpoint = ctx.GetEndpoint();

    if (endpoint != null)
    {
        // An endpoint was matched.
        // ...
    }

    await next();
});

app.UseEndpoints(endpoints => endpoints.MapControllers());

huangapple
  • 本文由 发表于 2020年1月3日 16:43:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/59575446.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定