请求入关的前哨战-路由

为什么大多现代WEB框架引入路由?

以前webform 时代一个一个URL都是带后缀的,具体对应到磁盘上的一个文件,这样的方式不灵活,安全性低,所以引入了路由的概念

路由到底是什么?

在.netcore 中,路由本质上就是中间件,何以见得?我们如果输入的URL没有任何路由匹配,返回的就是404,想过没有为什么?这是因为路由没匹配到后交给下一个中间件,最后一个中间件返回的就是404.

而且是两个中间件,各司其职。

UseRouting:请求进到中间件管道模型后,负责匹配URL到Action,

UseEndpoints:程序启动时候负责收集程序集中的controller 的Action,并转换controller的action到EndPoint, 在Endpoint被匹配后执行Action。

为什么完成路由功能需要2个中间件?

上述两件事情好像一个中间件也能完成,是的,但是有时候Action 需要授权,在加入授权中间件的时候,授权中间件只能加载在上述两个中间件之间,UseRouting 中间件匹配到Endpoint后,把Endpoint的信息附加到HttpContext 上下文中,授权中间件就可以拦截HttpContext中,根据其EndPoint 来做授权处理。

路由处理和终端中间件有什么异同?

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    // Approach 1: Writing a terminal middleware.
    app.Use(next => async context =>
    {
        if (context.Request.Path == "/")
        {
            await context.Response.WriteAsync("Hello terminal middleware!");
            return;
        }

        await next(context);
    });

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        // Approach 2: Using routing.
        endpoints.MapGet("/Movie", async context =>
        {
            await context.Response.WriteAsync("Hello routing!");
        });
    });
}

两者都可以终结 管道请求。

终端中间件位置很随意,可以手动的放置在任何地方,而Endpoint一般是在管道的末尾(人为在UseEndpoint后再添加中间件除外)

终端中间件执行效率高,但是一般不推荐,因为需要整合其它比如UserAutorization or UseCors 需要手动处理

 

集中式路由

特性路由

posted @ 2021-01-04 21:41  LearningAlbum  阅读(84)  评论(0)    收藏  举报