Endpoint路由

在ASP.NET Core 2.2中,新增了一种路由,叫做Endpoint(终结点)路由。本文将以往的路由系统称为传统路由

本文通过源码的方式介绍传统路由和Endpoint路由部分核心功能和实现方法,具体功能上的差异见官方文档

在升级到ASP.NET Core 2.2后,会自动启用Endpoint路由。如果要恢复以往的实现逻辑,需要加入以下代码:

services.AddMvc(options => options.EnableEndpointRouting = false)
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

本文分析的源代码基于ASP.NET Core 2.2.3版本的源代码

Endpoint作用

Endpoint路由与传统路由的区别在于,传统路由UrlAction对应关系的处理是在UseMvc中做的。我们无法根据Url获取对应的Action然后进行处理。

Endpoint就是将UrlAction的映射关系从Mvc中拆离,作为独立使用的中间件。

由此带来的好处是我们可以在其他的中间件中使用ControllerAction上的一些信息,例如Attruibute

框架也提供了LinkGenerator类来直接根据Endpoint生成链接,不再需要HttpContext的信息。

另外也提升了一些RPS(Requests per Second)。

不过目前Endpoint依然是在UseMvc中调用,更多开放的使用方式会在ASP.NET Core 3.0中实现。

启用Endpoint路由

源代码见Github。也可以获取源代码到本地看。

MvcApplicationBuilderExtensions.cs文件72行的UseMvc方法中我们可以看到以下代码:

var options = app.ApplicationServices.GetRequiredService<IOptions<MvcOptions>>();

if (options.Value.EnableEndpointRouting)
{
...
}
else
{
...
}

if之中是Endpoint路由的逻辑,else是传统路由的逻辑。

MvcOptions的构造方法如下所示,EnableEndpointRouting是通过CompatibilitySwitch来控制默认值的,这就是CompatibilityVersion.Version_2_2启用Endpoint路由的原因。

public MvcOptions()
{
// ...
_enableEndpointRouting = new CompatibilitySwitch<bool>(nameof(EnableEndpointRouting));
// ...
}

Endpoint路由实现原理

MvcApplicationBuilderExtensions.cs文件的92-123行的代码是将所有的Controller中的Action转换成Endpoint

在129行的UseEndpointRouting中,添加了一个EndpointRoutingMiddleware的中间件,这个中间件就是从所有的Endpoint中找到当前路由对应的Endpoint,然后放到Feature集合中。

在132行的UseEndpoint中,添加了一个EndpointMiddleware中间件,这个中间件是将EndpointRoutingMiddleware中找到的Endpoint取出,并调用RequestDelegateRequestDelegate是预处理过的Url对应的Action方法。

UseMvc方法里,UseEndpointRoutingUseEndpoint是连续的两个中间件,而UseEndpoint是请求的结束,这意味着我们自定义的中间件无法取得Endpoint信息。

但是通过手动调用UseEndpointRouting,我们还是可以拿到Endpoint路由信息的。

使用示例

下面展示一个使用示例。

定义一个LogAttribute类,并包含一个Message属性,在Action上声明使用。

定义一个EndpointTestMiddleware中间件,输出LogAttributeMessage属性。

手动调用UseEndpointRouting,然后调用我们定义的EndpointTestMiddleware中间件。

// Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseEndpointRouting(); app.UseMiddleware<EndpointTestMiddleware>(); app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
// EndpointTestMiddleware.cs
public class EndpointTestMiddleware
{
private RequestDelegate _next; public EndpointTestMiddleware(RequestDelegate next)
{
_next = next;
} public async Task Invoke(HttpContext httpContext)
{
var endpoint = httpContext.Features.Get<IEndpointFeature>()?.Endpoint;
if (endpoint == null)
{
await _next(httpContext);
return;
}
var attruibutes = endpoint.Metadata.OfType<LogAttribute>();
foreach (var attribute in attruibutes)
{
Debug.WriteLine("------------------------------------------------------------------------");
Debug.WriteLine(attribute.Message);
Debug.WriteLine("------------------------------------------------------------------------");
}
await _next(httpContext);
}
}
// LogAttribute.cs
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public sealed class LogAttribute : Attribute
{
public LogAttribute(string message)
{
Message = message;
} public string Message { get; set; }
}
// HomeController.cs
public class HomeController : Controller
{
[Log("Index")]
public IActionResult Index()
{
return View();
} [Log("Privacy")]
public IActionResult Privacy()
{
return View();
}
}

这样的话,我们可以在我们自己的中间件中拿到Endpoint信息,然后找到Controller上的LogAttribute,然后输出Message

总结

Endpoint是ASP.NET Core 2.2中一种新的路由机制,它解决了传统路由难以扩展的问题,解决了传统路由与MVC过于耦合的问题,并提升了一定的RPS。

本文介绍了Endpoint路由,简单分析了Endpoint的实现原理,并给出了一个使用的示例。

参考链接:

  1. https://devblogs.microsoft.com/aspnet/asp-net-core-2-2-0-preview1-endpoint-routing/
  2. https://www.stevejgordon.co.uk/asp-net-core-first-look-at-global-routing-dispatcher
  3. https://rolandguijt.com/endpoint-routing-in-asp-net-core-2-2-explained/

ASP.NET Core 2.2中的Endpoint路由的更多相关文章

  1. ASP.NET Core 3.0中使用动态控制器路由

    原文:Dynamic controller routing in ASP.NET Core 3.0 作者:Filip W 译文:https://www.cnblogs.com/lwqlun/p/114 ...

  2. 避免在ASP.NET Core 3.0中为启动类注入服务

    本篇是如何升级到ASP.NET Core 3.0系列文章的第二篇. Part 1 - 将.NET Standard 2.0类库转换为.NET Core 3.0类库 Part 2 - IHostingE ...

  3. asp.net core 3.0 中使用 swagger

    asp.net core 3.0 中使用 swagger Intro 上次更新了 asp.net core 3.0 简单的记录了一下 swagger 的使用,那个项目的 api 比较简单,都是匿名接口 ...

  4. 探索ASP.Net Core 3.0系列二:聊聊ASP.Net Core 3.0 中的Startup.cs

    原文:探索ASP.Net Core 3.0系列二:聊聊ASP.Net Core 3.0 中的Startup.cs 前言:.NET Core 3.0 SDK包含比以前版本更多的现成模板. 在本文中,我将 ...

  5. 将终结点图添加到你的ASP.NET Core应用程序中

    在本文中,我将展示如何使用DfaGraphWriter服务在ASP.NET Core 3.0应用程序中可视化你的终结点路由.上面文章我向您演示了如何生成一个有向图(如我上篇文章中所示),可以使用Gra ...

  6. ASP.NET Core HTTP 管道中的那些事儿

    前言 马上2016年就要过去了,时间可是真快啊. 上次写完 Identity 系列之后,反响还不错,所以本来打算写一个 ASP.NET Core 中间件系列的,但是中间遇到了很多事情.首先是 NPOI ...

  7. ASP.NET Core 1.0 中的依赖项管理

    var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...

  8. 在ASP.NET Core 1.0中如何发送邮件

    (此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:目前.NET Core 1.0中并没有提供SMTP相关的类库,那么要如何从ASP.NE ...

  9. ASP.NET Core 1.0 中使用 Swagger 生成文档

    github:https://github.com/domaindrivendev/Ahoy 之前文章有介绍在ASP.NET WebAPI 中使用Swagger生成文档,ASP.NET Core 1. ...

随机推荐

  1. xadmin增加用户 除了账号和密码 添加其他信息

    默认xadmin在添加账号的时候只有账号和密码 我们可以添加其他信息 打开源码 xadmin -> plugins -> auth -> 找到self.form = UserCrea ...

  2. socket failed: EACCES

    参考 https://blog.csdn.net/ct_ts/article/details/80010208 <uses-permission android:name=“android.pe ...

  3. 8-13、Python 散列复习

    1.{} 输入是花括号 myCat = { 'size':'fat', 'color':'gray', 'disposition':'loud'}   键:值 myCat['size'] = fat ...

  4. Python+Selenium学习--案例介绍

    1. 前言 前面讲解了那么多selenium的基础知识,下面用一个简单案例来介绍,此案例主要实现,运行测试,自动生成html报告,并发生邮件. 2. 测试案例 2.1 目录结构介绍 conf:配置信息 ...

  5. 9.22 Sans-serif VS Serif

    在FCC做题遇到了sans-serif 以及 serif字体,第一次遇到,所以查了一下: 西方国家字母体系分为两类:serif 以及sans serif. 原来Sans-serif是无衬线字体,没有额 ...

  6. swift 需求: 导航栏和HeaderView 使用一个背景图片。

    问题界面 需求: 导航栏和HeaderView 使用一个背景图片.解决方案: 让 导航栏 变成透明. override func viewWillAppear(_ animated: Bool) { ...

  7. maven小结

    1.首先要安装maven,我的在: F:\apache-maven-3.0.4 2.手动创建本地仓库的地址为:F:\.m2\repository 3.从windows的环境变量中增加了:M2_HOME ...

  8. input type="file"多图片上传 原生html传递的数组集合

    单个的input type="file"表单也是可以实现多图片上传的 代码如下: <form action="manypic.php" method=&q ...

  9. python 实现 Fortran的读取10*0以及换行读问题

    思路,用read来全部读取,然后替换带*的元素来解决.代码如下 import numpy as np import re inf = open('SF.usr') title = inf.readli ...

  10. Eclipse 中打开 python 交互窗口