最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

.Net Core路由處理的知識點與方法總結(jié)

 更新時間:2021年04月12日 12:12:05   作者:小世界的野孩子  
這篇文章主要給大家介紹了關于.Net Core路由處理的知識點與方法的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

前言

  用戶請求接口路由,應用返回處理結(jié)果。應用中如何匹配請求的數(shù)據(jù)呢?為何能如此精確的找到對應的處理方法?今天就談談這個路由。路由負責匹配傳入的HTTP請求,將這些請求發(fā)送到可以執(zhí)行的終結(jié)點。終結(jié)點在應用中進行定義并且在應用啟動的時候進行配置,也就是在中間件中進行處理。

路由基礎知識

  在項目新建的時候都會自動生成路由相關代碼。在Startup.Configure中的中間件管道注冊的。主要涉及到的則是UseRouting和UseEndpoints中間件。

    UseRouting向中間件添加路由匹配。此中間件還會查看應用中定義的終結(jié)點集。也就是把應用中的路由統(tǒng)統(tǒng)注冊到中間件管道,方便請求的時候進行匹配。

    UseEndpoints向中間件添加終結(jié)點執(zhí)行。會運行相關聯(lián)的委托。簡單將就是路由匹配之后的處理事件運行。

        // 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是/的時候需要執(zhí)行的委托、如果這里的請求不是Get請求或者不是"/",那么沒有路由匹配,則會返回404。同時指定匹配模式的還有MapDelete、MapMethods、MapPost、MapPut、Map等。

終結(jié)點

  上面講的MapGet或者未用到MapPost等就是用于定義終結(jié)點的。它們都包含有兩個參數(shù),一個是用于Url匹配的,另外一個就是需要執(zhí)行的委托。這里在不一樣的應用中都采用了不同的終結(jié)點定義方法

  • 用于 Razor Pages 的 MapRazorPages
  • 用于控制器的 MapControllers
  • 用于 SignalR 的 MapHub
  • 用于 gRPC 的 MapGrpcService

  那么我們?nèi)绻枰褂玫搅耸跈?quán)模塊將如何處理呢,終結(jié)點也有相對應的處理方式。下面就展示將授權(quán)中間件和路由一起使用,MapHealthChecks添加運行狀況檢查終結(jié)點。后面跟著的RequireAuthorization則是將授權(quán)策略添加到端點。

           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中間的,如此寫法則是為了授權(quán)策略能在UseRouting中查找終結(jié)點,但是能在UseEndpoints發(fā)送到終結(jié)點執(zhí)行之前應用所選擇的授權(quán)策略

終結(jié)點元數(shù)據(jù)

  上面的示例展示了運行狀況檢查終結(jié)點附加了授權(quán)策略。添加的授權(quán)策略是額外數(shù)據(jù),也就是終結(jié)點元數(shù)據(jù)。

  • 可以通過路由感知中間件來處理元數(shù)據(jù)。
  • 元數(shù)據(jù)可以是任意的 .NET 類型。

  上面提到元數(shù)據(jù)可以是人意的.NET類型,那么具體到底是什么呢?元數(shù)據(jù)如何使用呢?

         // 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<AuditPolicyAttribute>()?.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; }
    }

  看上面的示例中,在終結(jié)點綁定"/sensitive"的時候會附加元數(shù)據(jù)WithMetadata。當訪問“/”的時候會輸出"Hello world!"。但是在app.Use中并不會執(zhí)行輸出"處理事務邏輯",因為并沒有匹配的元數(shù)據(jù)。但是當執(zhí)行"/sensitive"的時候就會輸出Console.WriteLine("開始處理事務邏輯");。因為在終結(jié)點定義的時候添加了元數(shù)據(jù)。元數(shù)據(jù)可以是人意.NET類型。上面的元數(shù)據(jù)也是我們自定義Class。

比較終端中間件和路由

  上面我們使用app.Use來檢測匹配元數(shù)據(jù),如果匹配成功我們就執(zhí)行對應的操作。我們稱之為終端中間件,為什么是終端中間件呢,因為這里會停止搜索執(zhí)行匹配和操作、最后返回。

  那么相比較下終端中間件和路由有什么區(qū)別呢?

這兩種方法都允許終止處理管道:終端中間件允許在管道中的任意位置放置中間件:

  • 中間件通過返回而不是調(diào)用 next 來終止管道。
  • 終結(jié)點始終是終端。

終端中間件允許在管道中的任意位置放置中間件:

  • 終結(jié)點在 UseEndpoints 位置執(zhí)行。

終端中間件允許任意代碼確定中間件匹配的時間:

  • 自定義路由匹配代碼可能比較復雜,且難以正確編寫。
  • 路由為典型應用提供了簡單的解決方案。
  • 大多數(shù)應用不需要自定義路由匹配代碼。

帶有中間件的終結(jié)點接口,如 UseAuthorization 和 UseCors。

  • 通過 UseAuthorization 或 UseCors 使用終端中間件需要與授權(quán)系統(tǒng)進行手動交互

設置傳統(tǒng)路由

  上面我們知道了通過UseRouting向中間件添加路由匹配,然后通過UseEndpoints定義終結(jié)點去執(zhí)行匹配委托。那么在MVC模式中如何設置呢?我們看看傳統(tǒng)路由的設置方法。

         app.UseEndpoints(endpoints =>
            {
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            });

  上面我們設置傳統(tǒng)路由的時候采用的是endpoints.MapControllerRoute();,其中附帶有兩個參數(shù),一個是名稱default,第二個則是路由模板。我們看路由模板{controller=Home}/{action=Index}/{id?},那么在匹配Url路徑的時候,例如執(zhí)行路徑 WeatherForecast/Index/5。那么則會匹配控制器為WeatherForecast,其中方法是Index并且參數(shù)是int類型的一個處理方法。

REST Api 的屬性路由

  上面講的是傳統(tǒng)路由設置,那么對于Api項目的路由設置是如何的呢?REST Api 應使用屬性路由將應用功能建模為一組資源。我們看下示例代碼

     // 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調(diào)用。映射屬性路由。我們看在使用的時候?qū)傩月酚傻氖褂梅绞健?/p>

Route[]

      下面的示例中我們采用的是Route[]的方式,它既可單獨作用域控制器也可單獨作用域action。也可同時使用。

  [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {

        [Route("Index")]
        public string Index(int? id)
        {
            return "Test";
        }
    }

    [ApiController]
    [Route("[controller]/[action]")]
    public class WeatherForecastController : ControllerBase
    {
        public string Index(int? id)
        {
            return "Test";
        }
    }
    [ApiController]
    public class WeatherForecastController : ControllerBase
    {
        [Route("[controller]/Index")]
        public string Index(int? id)
        {
            return "Test";
        }
    }

Http[Verb]

      采用Http[Verb]的方式那就僅僅能作用在action上了。比如下面的就直接在Index上方寫[HttpGet

("[controller]/Index")],其他就是HttpPost、HttpDelete等等操作
   [ApiController]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet("[controller]/Index")]
        public string Index(int? id)
        {
            return "Test";
        }
    }

Route[]和Http[Verb]混合使用

      有時在實際運用中也可以采取兩種方式混合使用的,例如下面的示例在控制器采用Route[],在action采用Http[Verb]。因為一般定義Api的時候我們不僅要標注action名稱,我們還需要知道action的請求方式。

  [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {

        [HttpGet("Index")]
        public string Index(int? id)
        {
            return "Test";
        }
    }

總結(jié)

到此這篇關于.Net Core路由處理的文章就介紹到這了,更多相關.Net Core路由處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

象山县| 青川县| 尖扎县| 水城县| 昌都县| 陆河县| 安泽县| 曲水县| 安岳县| 开阳县| 木里| 鹿邑县| 碌曲县| 鹿邑县| 民勤县| 麻栗坡县| 长春市| 红河县| 东海县| 行唐县| 临沧市| 泰和县| 防城港市| 星子县| 理塘县| 元朗区| 云和县| 蓬安县| 衡山县| 包头市| 榆社县| 屏东市| 阜平县| 东平县| 田阳县| 上高县| 扶余县| 新巴尔虎右旗| 开鲁县| 承德县| 班玛县|