繁体   English   中英

使用 app.UseMvc() 或 app.UseEndpoints 在 asp.net core mvc 项目中设置路由有什么区别?

[英]What is difference between setting up routing in asp.net core mvc project with app.UseMvc() or app.UseEndpoints?

我知道当从 asp.net 2.2 迁移到 3 app.UseMvc() 行时,startup.cs 文件的配置方法被 app.UseRouting(); 替换; app.UseAuthorization(); app.UseEndpoints();。

谁能解释一下 app.UseEndpoints() 和 app.UseMvc() 是如何在内部工作的?

在asp.net core mvc 2.2框架下,要使用传统路由,必须在UseMVC中间件中配置IRouteBuilder接口。

在应用Startup的Configure方法中,默认路由设置如下:

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
{

在对 UseMvc 的调用中,MapRoute 用于创建单个路由,也称为默认路由。 大多数 MVC 应用程序使用带有模板的路由。 可以使用默认路由的便捷方法:

app.UseMvcWithDefaultRoute();

UseMvc 和 UseMvcWithDefaultRoute 可以将 RouterMiddleware 的实例添加到中间件管道中。 MVC 不直接与中间件交互,而是使用路由来处理请求。 MVC 通过 MvcRouteHandler 的实例连接到路由。

UseMvc 不直接定义任何路由。 它在属性路由的路由集合中添加了占位符{controller=Home}/{action=Index}/{id?}。 通过重载UseMvc(Action),允许用户添加自己的路由,也支持属性路由。

UseEndpoints :执行匹配的端点。

它将路由匹配和解析功能与端点执行功能分开,直到现在,这些功能都与 MVC 中间件捆绑在一起。

首先,你可以看看他们的源代码

public static IApplicationBuilder UseEndpoints(this IApplicationBuilder builder, Action<IEndpointRouteBuilder> configure)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        if (configure == null)
        {
            throw new ArgumentNullException(nameof(configure));
        }

        VerifyRoutingServicesAreRegistered(builder);

        VerifyEndpointRoutingMiddlewareIsRegistered(builder, out var endpointRouteBuilder);

        configure(endpointRouteBuilder);

        // Yes, this mutates an IOptions. We're registering data sources in a global collection which
        // can be used for discovery of endpoints or URL generation.
        //
        // Each middleware gets its own collection of data sources, and all of those data sources also
        // get added to a global collection.
        var routeOptions = builder.ApplicationServices.GetRequiredService<IOptions<RouteOptions>>();
        foreach (var dataSource in endpointRouteBuilder.DataSources)
        {
            routeOptions.Value.EndpointDataSources.Add(dataSource);
        }

        return builder.UseMiddleware<EndpointMiddleware>();
    }

ASP.NET Core 3 使用改进的端点路由,这通常会对应用程序内的路由提供更多控制。 端点路由分为两个独立的步骤:

在第一步中,请求的路由与配置的路由再次匹配,以确定正在访问的路由。

在最后一步中,正在评估确定的路由并调用相应的中间件,例如 MVC。

这两个步骤由 app.UseRouting() 和 app.UseEndpoints() 设置。 前者将注册运行逻辑以确定路由的中间件。 然后后者将执行该路线。

另外,请参考:

https://asp.net-hacker.rocks/2019/08/12/aspnetcore30-look-into-startup.html https://aregcode.com/blog/2019/dotnetcore-understanding-aspnet-endpoint-routing/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM