京东6.18大促主会场领京享红包更优惠

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 7261|回复: 0

.Net Core路由处理的知识点与方法总结

[复制链接]

19

主题

0

回帖

10

积分

新手上路

积分
10
发表于 2021-7-25 20:45:32 | 显示全部楼层 |阅读模式 来自 中国
前言
5 I( ^$ _+ o( V0 B  `2 y
% m: W8 O9 N% W9 n7 O( g) U  用户请求接口路由,应用返回处理结果。应用中如何匹配请求的数据呢?为何能如此精确的找到对应的处理方法?今天就谈谈这个路由。路由负责匹配传入的HTTP请求,将这些请求发送到可以执行的终结点。终结点在应用中进行定义并且在应用启动的时候进行配置,也就是在中间件中进行处理。7 K1 |- S! H2 ?" m
路由基础知识/ O6 E0 E8 {8 i  x* N
/ z6 K) I) G; h

$ J# D, w4 ^# n& W* C  在项目新建的时候都会自动生成路由相关代码。在Startup.Configure中的中间件管道注册的。主要涉及到的则是UseRouting和UseEndpoints中间件。
, Q9 \- w. H7 ]3 ~$ u" B3 t; `9 l/ s: c0 p    UseRouting向中间件添加路由匹配。此中间件还会查看应用中定义的终结点集。也就是把应用中的路由统统注册到中间件管道,方便请求的时候进行匹配。
' b2 T8 x6 v7 L4 E- a    UseEndpoints向中间件添加终结点执行。会运行相关联的委托。简单将就是路由匹配之后的处理事件运行。
  1. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)        {            if (env.IsDevelopment())            {                app.UseDeveloperExceptionPage();            }            app.UseRouting();            app.UseEndpoints(endpoints =>            {                endpoints.MapGet("/", async context =>                {                    await context.Response.WriteAsync("Hello World!");                });            });        }
复制代码
  例如上面的代码就是HTPP GET 请求并且Url是/的时候需要执行的委托、如果这里的请求不是Get请求或者不是"/",那么没有路由匹配,则会返回404。同时指定匹配模式的还有MapDelete、MapMethods、MapPost、MapPut、Map等。3 o+ h3 q3 r- j% {4 K) Y
终结点& d& m; @1 U$ a7 a, G9 c
0 E5 F! n6 W3 K  v7 \( }

3 w, }$ g+ R" `0 ~9 p' r! g( u* O  上面讲的MapGet或者未用到MapPost等就是用于定义终结点的。它们都包含有两个参数,一个是用于Url匹配的,另外一个就是需要执行的委托。这里在不一样的应用中都采用了不同的终结点定义方法1 T# [) W5 m8 }6 s
        : n- S' z: _: g" z, s6 M! N
  • 用于 Razor Pages 的 MapRazorPages   
    . x: g% {/ A2 p5 k7 r% t9 ?. m! |
  • 用于控制器的 MapControllers    1 S) P) p: [5 a/ m3 \/ H4 n$ `- G. Q
  • 用于 SignalR 的 MapHub   
    ( W. R2 h7 p8 |0 G% K7 V* H
  • 用于 gRPC 的 MapGrpcService
      c" E2 j: s5 u0 l0 P4 M; q4 V
  那么我们如果需要使用到了授权模块将如何处理呢,终结点也有相对应的处理方式。下面就展示将授权中间件和路由一起使用,MapHealthChecks添加运行状况检查终结点。后面跟着的RequireAuthorization则是将授权策略添加到端点。
  1. app.UseRouting();            app.UseAuthentication();            app.UseAuthorization();            app.UseEndpoints(endpoints =>            {                endpoints.MapHealthChecks("/healthz").RequireAuthorization();                endpoints.MapGet("/", async context =>                {                    await context.Response.WriteAsync("Hello World!");                });            });
复制代码
  而且我们看中间的使用顺序,UseAuthentication、UseAuthorization是穿插在UseRouting和UseEndpoints中间的,如此写法则是为了授权策略能在UseRouting中查找终结点,但是能在UseEndpoints发送到终结点执行之前应用所选择的授权策略3 H: H/ J( Z5 }6 l' {
终结点元数据; v8 l7 q' s7 a( w4 s8 b
& M0 ^/ j6 M% L4 Q% C: M
7 L# A3 v& t5 ~- F
  上面的示例展示了运行状况检查终结点附加了授权策略。添加的授权策略是额外数据,也就是终结点元数据。
. n+ H2 e" q. |5 B
       
    ) c3 x$ z, t8 ~) }
  • 可以通过路由感知中间件来处理元数据。   
    1 ^) H/ X* N3 t) E% t9 G
  • 元数据可以是任意的 .NET 类型。! m; C+ C- p* ]8 \
  上面提到元数据可以是人意的.NET类型,那么具体到底是什么呢?元数据如何使用呢?
  1. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)        {            if (env.IsDevelopment())            {                app.UseDeveloperExceptionPage();            }            app.UseRouting();            app.Use(next => context =>            {                var endpoint = context.GetEndpoint();                if (endpoint?.Metadata.GetMetadata()?.NeedsAudit ==true)                {                    Console.WriteLine("开始处理事务逻辑");                    Console.WriteLine($"ACCESS TO SENSITIVE DATA AT: {DateTime.UtcNow}");                }                return next(context);            });            app.UseEndpoints(endpoints =>            {                endpoints.MapGet("/", async context =>                {                    await context.Response.WriteAsync("Hello world!");                });                // Using metadata to configure the audit policy.                endpoints.MapGet("/sensitive", async context =>                {                    await context.Response.WriteAsync($"sensitive data{DateTime.UtcNow}");                })                .WithMetadata(new AuditPolicyAttribute(needsAudit: true));            });        }    }    public class AuditPolicyAttribute : Attribute    {        public AuditPolicyAttribute(bool needsAudit)        {            NeedsAudit = needsAudit;        }        public bool NeedsAudit { get; }    }
复制代码
  看上面的示例中,在终结点绑定"/sensitive"的时候会附加元数据WithMetadata。当访问“/”的时候会输出"Hello world!"。但是在app.Use中并不会执行输出"处理事务逻辑",因为并没有匹配的元数据。但是当执行"/sensitive"的时候就会输出Console.WriteLine("开始处理事务逻辑");。因为在终结点定义的时候添加了元数据。元数据可以是人意.NET类型。上面的元数据也是我们自定义Class。; J9 V' x% B. k# Z
比较终端中间件和路由
# x) ]( @; O* S

* _# e! E2 c9 ~' T3 u
5 n2 ^$ b# B  `# p  上面我们使用app.Use来检测匹配元数据,如果匹配成功我们就执行对应的操作。我们称之为终端中间件,为什么是终端中间件呢,因为这里会停止搜索执行匹配和操作、最后返回。8 u9 U. N$ y- {* b: [! u' F
  那么相比较下终端中间件和路由有什么区别呢?
7 ^$ M4 l2 J# ~  _5 |: Y这两种方法都允许终止处理管道:终端中间件允许在管道中的任意位置放置中间件:
' l0 ]0 I! q1 `' P0 l
        : K. r. i8 P: c& M
  • 中间件通过返回而不是调用 next 来终止管道。   
    6 O0 J& \0 ^/ {0 s8 D" ]7 `! c
  • 终结点始终是终端。
    3 V' R/ v! c6 y5 E  I
终端中间件允许在管道中的任意位置放置中间件:
5 x7 _; s' ]6 A. v5 ?$ t
       
    ) Q0 ?" c( H, B! L% n
  • 终结点在 UseEndpoints 位置执行。
    ! h+ U) e4 Y6 i7 r) T
终端中间件允许任意代码确定中间件匹配的时间:+ ]  [1 q* \8 }
        3 |+ y* l; [( Q' N$ g; J
  • 自定义路由匹配代码可能比较复杂,且难以正确编写。   
    2 }* q, d1 u" s' O, K, k
  • 路由为典型应用提供了简单的解决方案。   
    ( d$ @: T: s) N
  • 大多数应用不需要自定义路由匹配代码。
    6 d  J: v. F9 h
带有中间件的终结点接口,如 UseAuthorization 和 UseCors。
; ~" R) H1 o  D6 Q9 O
       
    / k$ e$ B4 H  U% s9 q& C& B4 C' ?
  • 通过 UseAuthorization 或 UseCors 使用终端中间件需要与授权系统进行手动交互8 r" d9 T8 G1 p1 c
设置传统路由0 d  f% J3 J5 g! Y1 E1 N
# q* d) V- K/ O& D8 l) L

% S3 J) d& w  N; d  上面我们知道了通过UseRouting向中间件添加路由匹配,然后通过UseEndpoints定义终结点去执行匹配委托。那么在MVC模式中如何设置呢?我们看看传统路由的设置方法。
  1. app.UseEndpoints(endpoints =>            {                app.UseEndpoints(endpoints =>                {                    endpoints.MapControllerRoute(                        name: "default",                        pattern: "{controller=Home}/{action=Index}/{id?}");                });            });
复制代码
  上面我们设置传统路由的时候采用的是endpoints.MapControllerRoute();,其中附带有两个参数,一个是名称default,第二个则是路由模板。我们看路由模板{controller=Home}/{action=Index}/{id?},那么在匹配Url路径的时候,例如执行路径 WeatherForecast/Index/5。那么则会匹配控制器为WeatherForecast,其中方法是Index并且参数是int类型的一个处理方法。" T0 W; h4 u$ O7 O; q; ^2 y
REST Api 的属性路由) ~8 \, J5 H- H$ H: \: [; G- |% K
5 k) f# P. V' n: }( ]9 V! h

$ i& Z/ R0 X* F9 W  上面讲的是传统路由设置,那么对于Api项目的路由设置是如何的呢?REST Api 应使用属性路由将应用功能建模为一组资源。我们看下示例代码
  1. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)        {            if (env.IsDevelopment())            {                app.UseDeveloperExceptionPage();            }            app.UseRouting();            app.UseAuthorization();            app.UseEndpoints(endpoints =>            {                endpoints.MapControllers();            });        }
复制代码
  在上面的代码中使用MapControllers调用。映射属性路由。我们看在使用的时候属性路由的使用方式。
- D$ @( q( v- L6 LRoute[]  k) D0 o, G) o) P% K* Q* J. h' Y
      下面的示例中我们采用的是Route[]的方式,它既可单独作用域控制器也可单独作用域action。也可同时使用。
  1. [ApiController]    [Route("[controller]")]    public class WeatherForecastController : ControllerBase    {        [Route("Index")]        public string Index(int? id)        {            return "Test";        }    }
复制代码
  1. [ApiController]    [Route("[controller]/[action]")]    public class WeatherForecastController : ControllerBase    {        public string Index(int? id)        {            return "Test";        }    }
复制代码
  1. [ApiController]    public class WeatherForecastController : ControllerBase    {        [Route("[controller]/Index")]        public string Index(int? id)        {            return "Test";        }    }
复制代码
Http[Verb], K7 K. m1 u# k
      采用Http[Verb]的方式那就仅仅能作用在action上了。比如下面的就直接在Index上方写[HttpGet
  1. ("[controller]/Index")],其他就是HttpPost、HttpDelete等等操作   [ApiController]    public class WeatherForecastController : ControllerBase    {        [HttpGet("[controller]/Index")]        public string Index(int? id)        {            return "Test";        }    }
复制代码
Route[]和Http[Verb]混合使用
; J& o0 J" @2 N; M! X) w4 g, N. c  j, H
- V  l5 L: s" p8 N4 }( x( J
      有时在实际运用中也可以采取两种方式混合使用的,例如下面的示例在控制器采用Route[],在action采用Http[Verb]。因为一般定义Api的时候我们不仅要标注action名称,我们还需要知道action的请求方式。
  1. [ApiController]    [Route("[controller]")]    public class WeatherForecastController : ControllerBase    {        [HttpGet("Index")]        public string Index(int? id)        {            return "Test";        }    }
复制代码
总结' m! k" w* o& z

! j! T" y( w5 ^4 x6 @到此这篇关于.Net Core路由处理的文章就介绍到这了,更多相关.Net Core路由处理内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
6 {0 s. \$ V" D3 z- f  r" F4 R# L+ L2 ~% `
来源:http://www.jb51.net/article/209414.htm% ]* d+ R! [% |1 H/ O. O0 b( z
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

帖子地址: 

梦想之都-俊月星空 优酷自频道欢迎您 http://i.youku.com/zhaojun917
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|梦想之都-俊月星空 ( 粤ICP备18056059号 )|网站地图

GMT+8, 2026-3-20 12:45 , Processed in 0.056024 second(s), 23 queries .

Powered by Mxzdjyxk! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表