.Net Core Web Api_筆記12_自定義屬性路由

 


在前幾篇文章中我們都是用
微軟內建的RouteAttributeHttpMethodAttribute兩種屬性路由
而當我們不想用這兩種因為要重複寫太多
想要用自己封裝或客製過的屬性來定義路由
則可依賴.net core中的interface  IRouteTemplateProvider來實踐。


無論是RouteAttribute或者HttpMethodAttribute之所以能夠讓我們去透過在屬性上用標記方式
設置路由模板
主要都是因為他們都有去實作IRouteTemplateProvider該interface

RouteAttribute



HttpMethodAttribute


比方我們這裡想要自己有一種屬性標記
這裡我取名為[SuperManRoute(....)]
可再專案新建一個目錄取名為Services
新建一個Class 命名為SuperManRouteAttribute
然後去繼承Attribute這個Base Class
並實作IRouteTemplateProvider



這裡改寫如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
using Microsoft.AspNetCore.Mvc.Routing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NetCoreApiTest1.Services
{
    /// <summary>
    /// Custom Attribute Route
    /// </summary>
    public class SuperManRouteAttribute : Attribute, IRouteTemplateProvider
    {
        public string Template => "superman/[controller]";

        public int? Order => 1;

        public string Name { get; set; }
    }
}


外部使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NetCoreApiTest1.Services;
namespace NetCoreApiTest1.Controllers
{
    [SuperManRoute(Name ="CustomAttrRoute")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        [Route("")]     
        [Route("UserList")]    
        [Route("GetUsers")]
        public string Users()
        {
            return "users data...";
        }

    }
}






藉此就能做自定義封裝的路由屬性標記




留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題