.Net Core Web Api_笔记09_web api的属性路由模板两种写法_路由模板使用

在.net core mvc跟.net core web api专案中预设各自采用的一些配置
有不太一样的地方,在Startup.cs中

.net core (.net5) mvc专案

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyMVCTest0
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

        // 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();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

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

https://ithelp.ithome.com.tw/upload/images/20210911/20107452b9ZJLY6YOr.png

.net core (.net5) web api专案

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyApiTest0
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
        }

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

https://ithelp.ithome.com.tw/upload/images/20210911/20107452dggsZkoztg.png

在.net core api专案除了在ConfigureServices()服务注入中别於Mvc只有注入Controllers()而已
预设还会自动被配置为采用「属性路由」也就是MapControllers(),表示去对应控制器的属性路由,别於MVC的传统路由(Conventional routing)配置。

属性路由从[Route("")]当中进行设定
比方如下访问的路由就是
api/student

https://ithelp.ithome.com.tw/upload/images/20210911/20107452g0360a8QWK.png

而在action下也可进行相应的属性路由配置
比方要访问Show()则路由就是
api/student/display

https://ithelp.ithome.com.tw/upload/images/20210911/201074527IIyCxS8S8.png

而也可将属性路由去跟HTTP verb attributes(动作名词、HTTP动作动词)去结合
产生Route template for action 第二种缩减的写法

https://ithelp.ithome.com.tw/upload/images/20210911/20107452Uff1yV83GN.png

路由模板(Route Template):从Client端输入的URL如何匹配到Server端对应Action的路由
再白话一点说就是怎麽给Client端指定对应的Response跟Response之前的业务逻辑处理。

无论是MVC的传统路由或目前探讨的Web API属性路由
都涉及到要去配置Route Template的议题

於Route Template中分两种占位符(标记取代)
1.中方括号[] , 又固定只包含三种关键字[控制器]、[动作]、[区域]
[controller] , [action] , [area]

2.大花括号{} ,代表路由传入的参数值

以下面为例就是透过传入{id}过滤将对应person资料呈现

https://ithelp.ithome.com.tw/upload/images/20210911/20107452VWIgYW2L5l.png

而我们也可透过[action]的标记取代
来直接透过action method 名称来做访问

https://ithelp.ithome.com.tw/upload/images/20210911/20107452XlyaU6elTS.png

路由属性(RouteAttribute)

在 web api专案中可让我们不论在Controller层级或Action层级都能使用Route 属性
以下是微软对其封装的程序

#region 组件 Microsoft.AspNetCore.Mvc.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
// C:\Program Files\dotnet\packs\Microsoft.AspNetCore.App.Ref\5.0.0\ref\net5.0\Microsoft.AspNetCore.Mvc.Core.dll
#endregion

using Microsoft.AspNetCore.Mvc.Routing;
using System;

namespace Microsoft.AspNetCore.Mvc
{
    //
    // 摘要:
    //     Specifies an attribute route on a controller.
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class RouteAttribute : Attribute, IRouteTemplateProvider
    {
        //
        // 摘要:
        //     Creates a new Microsoft.AspNetCore.Mvc.RouteAttribute with the given route template.
        //
        // 参数:
        //   template:
        //     The route template. May not be null.
        public RouteAttribute(string template);

        public string Template { get; }
        //
        // 摘要:
        //     Gets the route order. The order determines the order of route execution. Routes
        //     with a lower order value are tried first. If an action defines a route by providing
        //     an Microsoft.AspNetCore.Mvc.Routing.IRouteTemplateProvider with a non null order,
        //     that order is used instead of this value. If neither the action nor the controller
        //     defines an order, a default value of 0 is used.
        public int Order { get; set; }
        public string Name { get; set; }
    }
}

在属性上面定义的RouteAttribute
可让我们除了一般route template之外
还能够去设置Name属性、Order属性(在HttpMethod属性或Route属性都能设置)

Name属性
HttpMethodAttribute.Name Property

RouteAttribute.Name Property

Gets the route name. The route name can be used to generate a link using a specific route, instead of relying on selection of a route based on the given set of route values.

有点类似替路由模板设置别名的感觉
https://ithelp.ithome.com.tw/upload/images/20210911/20107452vkvzMExvD6.png

可帮助我们去透过自订的路由名称来产生对应匹配的路由网址
换言之,藉由名称就能够得到路由模板。

以前几篇范例Student来改

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using MyApiTest1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyApiTest1.Controllers
{
    [Route("api/[controller]", Name = "StuApi")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        public LinkGenerator LinkGenerator { get; set; }

        public StudentController(LinkGenerator LinkGenerator)
        {
            this.LinkGenerator = LinkGenerator;
        }

        [HttpGet("/Student/GetUrl")]
        public string BuildUrl()
        {
            string url = LinkGenerator.GetPathByRouteValues("G_ID", new { id = 3 });
            return url;
        }

        [HttpGet("GetPersonById/{id}", Name = "G_ID")]
        public ActionResult<Person> GetPerson(int id)
        {
            List<Person> lsPersons = new List<Person>()
            {
                new Person(){Id=1,Name="Amy",Age=22,Sex="woman"},
                new Person(){Id=2,Name="Jessica",Age=25,Sex="woman"},
                new Person(){Id=3,Name="Banson",Age=24,Sex="man"}
            };
            return lsPersons.Where(item => item.Id == id).FirstOrDefault();
        }
    }
}

这里我们可以透过LinkGenerator 注入到建构子後
整个Controller的任一action中都能够去使用它
来去透过Name属性生成路由模板

测试效果即可看到
预设透过 路由模板/student/geturl
帮我们产生了一个新的路由模板去对person做资料过滤请求
https://ithelp.ithome.com.tw/upload/images/20210911/20107452JE0HjhQ4ky.png

Order属性
HttpMethodAttribute.Order Property

RouteAttribute.Order Property

Gets the route order. The order determines the order of route execution. Routes with a lower order value are tried first. If an action defines a route by providing an IRouteTemplateProvider with a non null order, that order is used instead of this value. If neither the action nor the controller defines an order, a default value of 0 is used.

则是让我们能够去设置路由顺序,预设当Order为Null时顺序为0。
数字愈小的优先权愈高

本篇同步发表至个人部落格
https://coolmandiary.blogspot.com/2021/09/net-core-web-api09web-api.html

Ref:

Convention Routing VS Attribute Routing
https://www.c-sharpcorner.com/article/convention-routing-vs-attribute-routing/

Routing to controller actions in ASP.NET Core
https://docs.microsoft.com/en-gb/aspnet/core/mvc/controllers/routing?view=aspnetcore-5.0#ordering-attribute-routes

ASP.NET Core 中的路由至控制器动作
https://docs.microsoft.com/zh-tw/aspnet/core/mvc/controllers/routing?view=aspnetcore-5.0#token-replacement-in-route-templates-controller-action-area

Web API Routing
https://www.tutorialsteacher.com/webapi/web-api-routing

Everything You Should Know About ASP .NET Core Routing
https://thecodeblogger.com/2021/05/28/everything-you-should-know-about-asp-net-core-routing/

Conventional vs Attribute Routing In ASP .NET Core Apps
https://thecodeblogger.com/2021/05/29/conventional-vs-attribute-routing-in-asp-net-core-apps/

Attribute Routing in ASP.NET Core
https://dotnetthoughts.net/attribute-routing-in-aspnet-core/

Understanding Routing Precedence In ASP.NET MVC And Web API
https://www.codeproject.com/Articles/1110613/Understanding-Routing-Precedence-in-ASP-NET-MVC-an
https://www.c-sharpcorner.com/article/understanding-routing-precedence-in-asp-net-mvc-and-web-api/

ASP.NET MVC Controller Attribute Route Precedence
https://www.softwareblogs.com/Posts/Details/18/aspnet-mvc-controller-attribute-route-precedence

Route Names and Route Orders in Attribute Routing
https://dotnettutorials.net/lesson/route-names-and-route-orders-attribute-routing/

What's the use of the Name parameter in RouteAttribute?
https://stackoverflow.com/questions/54412718/whats-the-use-of-the-name-parameter-in-routeattribute

ASP.NET WebApi 路由配置
https://www.cnblogs.com/Jeely/p/10956207.html

ASP. NET Web Api 2 学习笔记
http://blog.appx.tw/2018/06/01/asp-net-web-api-2-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98/


<<:  Gloud IAM 是什麽?

>>:  Day-10 全部都交给它就好的懒人怀旧神器 RetroTINK

15. STM32-I²C 介绍

介绍 I²C(Inter-Integrated Circuit)中文是内部整合电路,属於串列通讯汇流...

Day08 X 浏览器架构演进史 & 渲染机制

「在未来,浏览器会变得越来越强,以後我们可以在浏览器做越来越多事。」 身为常与浏览器共舞的 Web...

Day28 D3js Diagram常见的两点浪漫路径

D3js Diagram常见的两点浪漫路径 用途 在绘制diagram图表时,会用到的垂直水平连线,...

3+4 个 Google 判断付费连结 (Paid Links) 的方法

付费连结(Paid Links)在2010年代曾是个有争议的SEO灰色地带,但在多年後今日的SEO...

Day 12 - 物品借用纪录系统 (3) 系统完成

今天我们就把整个服务完成吧! 不知道大家顺利地收到通知了没? 我已经顺利收到罗~ 咦咦咦?发生什麽事...