簡體   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