欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解ASP.NET Core端点路由的作用原理

程序员文章站 2022-03-08 08:11:25
端点路由(endpoint routing)最早出现在asp.net core2.2,在asp.net core3.0提升为一等公民。endpoint routing的动机在端点路由出现之前,我们一般...

端点路由(endpoint routing)最早出现在asp.net core2.2,在asp.net core3.0提升为一等公民。

endpoint routing的动机

在端点路由出现之前,我们一般在请求处理管道的末尾,定义mvc中间件解析路由。这种方式意味着在处理管道中,mvc中间件之前的中间件将无法获得路由信息。

路由信息对于某些中间件非常有用,比如cors、认证中间件(认证过程可能会用到路由信息)。

同时端点路由提炼出端点概念,解耦路由匹配逻辑、请求分发。

endpoint routing中间件

由一对中间件组成:

userouting 将路由匹配添加到中间件管道。该中间件查看应用程序中定义的端点集合,并根据请求选择最佳匹配。useendpoints 将端点执行添加到中间件管道。

mapget、mappost等方法将 处理逻辑连接到路由系统;

其他方法将 asp.net core框架特性连接到路由系统。

  • maprazorpages for razor pages
  • mapcontrollers for controllers
  • maphub< thub> for signalr
  • mapgrpcservice< tservice> for grpc

处于这对中间件上游的 中间件: 始终无法感知 endpoint;
处于这对中间件之间的 中间件,将会感知到endpoint,并有能力执行附加处理逻辑;
useendpoint是一个终点中间件;
没有匹配,则进入useendpoint之后的中间件。

详解ASP.NET Core端点路由的作用原理

放置在useroutinguseendpoints之间的认证授权中间件可以:
感知被匹配的端点信息;在调度到endpoint之前,应用授权策略。

public void configure(iapplicationbuilder app, iwebhostenvironment env)
{
  if (env.isdevelopment())
  {
    app.usedeveloperexceptionpage();
  }

  // matches request to an endpoint.
  app.userouting();

  // endpoint aware middleware. 
  // middleware can use metadata from the matched endpoint.
  app.useauthentication();
  app.useauthorization();

  // execute the matched endpoint.
  app.useendpoints(endpoints =>
  {
    // configure the health check endpoint and require an authorized user.
    endpoints.maphealthchecks("/healthz").requireauthorization();

    // configure another endpoint, no authorization requirements.
    endpoints.mapget("/", async context =>
    {
      await context.response.writeasync("hello world!");
    });
  });
}

以上在/health定义了健康检查,该端点定义了iauthorizedatametadata,要求先认证再执行健康检查。

我们在userouting、useendpoints之间添加一点口水代码:感知端点:

  app.use(next => context =>
      {
        var endpoint = context.getendpoint();
        if (endpoint is null)
        {
          return task.completedtask;
        }
        console.writeline($"endpoint: {endpoint.displayname}");

        if (endpoint is routeendpoint routeendpoint)
        {
          console.writeline("endpoint has route pattern: " +
            routeendpoint.routepattern.rawtext);
        }

        foreach (var metadata in endpoint.metadata)
        {
          console.writeline($"endpoint has metadata: {metadata}");
        }
        return next(context);
      });

当请求/healthz时,感知到authorizeattribute metadata

详解ASP.NET Core端点路由的作用原理

故猜想认证授权中间件要对/healthz起作用,必然会对这个 authorizeattribute metadata有所反应。

于是翻阅githubauthorizationmiddleware3.0源码:发现确实关注了endpoint

// ---- 截取自https://github.com/dotnet/aspnetcore/blob/master/src/security/authorization/policy/src/authorizationmiddleware.cs-----
if (endpoint != null)
{
  context.items[authorizationmiddlewareinvokedwithendpointkey] = authorizationmiddlewarewithendpointinvokedvalue;
}
var authorizedata = endpoint?.metadata.getorderedmetadata<iauthorizedata>() ?? array.empty<iauthorizedata>();
var policy = await authorizationpolicy.combineasync(_policyprovider, authorizedata);
if (policy == null)
{
   await _next(context);
   return;
}
var policyevaluator = context.requestservices.getrequiredservice<ipolicyevaluator>();
......

authorizeattribute确实是实现了iauthorizedata接口。

binggo, 猜想得到源码验证。

结论

端点路由:允许asp.net core应用程序在中间件管道的早期确定要调度的端点,
以便后续中间件可以使用该信息来提供当前管道配置无法提供的功能。

这使asp.net core框架更加灵活,强化端点概念,它使路由匹配和解析功能与终结点分发功能脱钩。

https://github.com/dotnet/aspnetcore/blob/master/src/security/authorization/policy/src/authorizationmiddleware.cs

到此这篇关于详解asp.net core端点路由的作用原理的文章就介绍到这了,更多相关asp.net core端点路由内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!