c#代碼生成URL地址的示例
“頭疼”
自己在用Angular做項(xiàng)目時(shí),前端要請(qǐng)求后端數(shù)據(jù)時(shí)的代碼如下
this.http.get("url/xxx")
這是請(qǐng)求一個(gè)URL地址數(shù)據(jù)最簡(jiǎn)單的代碼,但是如此簡(jiǎn)單的代碼還會(huì)遇到一些頭疼的問(wèn)題
- URL地址拼寫(xiě)錯(cuò)誤,有可能折騰半天才發(fā)現(xiàn)😑
- 后端修改了地址沒(méi)通知到前端,測(cè)試不到位就炸了,不是所有項(xiàng)目都有那么規(guī)范的接口變更流程😑
- 查看代碼的時(shí)候,看著URL地址,這個(gè)地址用途是哈?還要翻接口文檔😑
“吃藥”
為了解決這個(gè)問(wèn)題,我們需要一個(gè)包含所有接口的文件
import { environment } from 'src/environments/environment'; export const WebAPI = { /** 授權(quán)控制器 */ Auth: { /** */ Controller: `${environment.host}/api/Auth`, /** GET 獲得用戶 */ GetUser: `${environment.host}/api/Auth/GetUser`, /** POST 登陸 */ Login: `${environment.host}/api/Auth/Login`, }, }
那么請(qǐng)求代碼就可以改成
this.http.get(WebAPI.Auth.GetUser)
但是維護(hù)這個(gè)文件是件吃力的事情,作為一個(gè)時(shí)刻想著如何偷懶的程序員,吃力的事情就讓計(jì)算機(jī)去干,所以寫(xiě)一個(gè)代碼生成工具。
工具代碼
public static class BuildWebApiToTS { public static string Build(Assembly assembly, string prefix = "api/") { List<Controller> controllers = GetApis(assembly); string code = CreateCode(controllers); return code.ToString(); } public static void BuildToFile(Assembly assembly, string path, string prefix = "api/") { var code = Build(assembly, prefix); string existsCode = ""; if (System.IO.File.Exists(path) == true) existsCode = System.IO.File.ReadAllText(path); if (existsCode != code) System.IO.File.WriteAllText(path, code); } #region 構(gòu)造代碼 public static string CreateCode(List<Controller> controllers, string prefix = "api/") { StringBuilder code = new StringBuilder(); code.AppendLine("import { environment } from 'src/environments/environment';"); code.AppendLine("export const WebAPI = {"); foreach (var coll in controllers.OrderBy(x => x.Name)) { code.AppendLine($" /** {coll.ApiComments?.Title} */"); code.AppendLine($" {coll.Name}: {{"); code.AppendLine($" Controller: `${{environment.host}}/{prefix}{coll.Name}`,"); foreach (var action in coll.Actions.OrderBy(x => x.Name)) { code.AppendLine($" /** {action.Type} {action.ApiComments?.Title} */"); code.AppendLine($" {action.Name}: `${{environment.host}}/{prefix}{coll.Name}/{action.Name}`,"); } code.AppendLine($" }},"); } code.AppendLine($"}};"); return code.ToString(); } #endregion #region 獲得接口清單 public static List<Controller> GetApis(Assembly assembly) { List<Controller> controllers = new List<Controller>(); var collTypes = assembly.GetTypes().Where(x => x.GetCustomAttributes(typeof(ApiControllerAttribute), false).Count() > 0); foreach (var collType in collTypes) { var controller = new Controller(collType.Name.Replace("Controller", "")); controller.ApiComments = collType.GetCustomAttribute<ApiCommentsAttribute>(); controllers.Add(controller); controller.Actions.AddRange(GetTypeMembers(collType, typeof(HttpGetAttribute), "GET")); controller.Actions.AddRange(GetTypeMembers(collType, typeof(HttpPostAttribute), "POST")); controller.Actions.AddRange(GetTypeMembers(collType, typeof(HttpPutAttribute), "PUT")); controller.Actions.AddRange(GetTypeMembers(collType, typeof(HttpDeleteAttribute), "DELETE")); } return controllers; } private static List<Action> GetTypeMembers(Type type, Type whereType, string saveType) { var actonTypes = type.GetMembers().Where(x => x.GetCustomAttributes(whereType, false).Count() > 0); List<Action> actons = new List<Action>(); foreach (var actonType in actonTypes) { var action = new Action(saveType, actonType.Name); action.ApiComments = actonType.GetCustomAttribute<ApiCommentsAttribute>(); actons.Add(action); } return actons; } public record Controller(string Name) { public ApiCommentsAttribute ApiComments { get; set; } public List<Action> Actions { get; set; } = new List<Action>(); } public record Action(string Type, string Name) { public ApiCommentsAttribute ApiComments { get; set; } } #endregion } public class ApiCommentsAttribute : Attribute { public string Title { get; set; } public ApiCommentsAttribute(string title) { Title = title; } }
使用代碼
#if DEBUG BuildWebApiToTS.BuildToFile(typeof(Program).Assembly, "ClientApp/src/app/web-api.ts"); #endif
上面代碼大概的流程就是
- 利用反射讀取程序集中包含
ApiControllerAttribute
特性的類(lèi) - 利用發(fā)射讀取
HttpGetAttribute
、HttpPostAttribute
、HttpPutAttribute
、HttpDeleteAttribute
特性的方法 - 根據(jù)需要的格式生成代碼
- 將代碼文件寫(xiě)入
ClientApp/src/app/web-api.ts
有了這個(gè)東西帶來(lái)以下好處
- URL地址拼寫(xiě)錯(cuò)誤問(wèn)題,不存在的🎉
- 后端修改了接口,前端直接編譯不過(guò),立即發(fā)現(xiàn)問(wèn)題🎉
- 鼠標(biāo)停留,接口注釋就顯示了🎉
以上就是c#代碼生成URL地址的方法的詳細(xì)內(nèi)容,更多關(guān)于c#代碼生成URL地址的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
WPF實(shí)現(xiàn)在線預(yù)覽和顯示W(wǎng)ord和PDF文件
這篇文章主要為大家詳細(xì)介紹了如何使用WPF實(shí)現(xiàn)在線預(yù)覽和顯示W(wǎng)ord和PDF文件,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-02-02基于C#實(shí)現(xiàn)SM2加簽驗(yàn)簽工具
這篇文章主要為大家詳細(xì)介紹了如何基于C#實(shí)現(xiàn)一個(gè)SM2加簽驗(yàn)簽工具,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-10-10關(guān)于C#中async/await的用法實(shí)例詳解
這篇文章主要介紹了關(guān)于C#中async/await的用法,今天寫(xiě)一個(gè)demo徹底搞明白async/await的用法,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-02-02C#開(kāi)發(fā)windows服務(wù)實(shí)現(xiàn)自動(dòng)從FTP服務(wù)器下載文件
這篇文章主要為大家詳細(xì)介紹了C#開(kāi)發(fā)windows服務(wù)實(shí)現(xiàn)自動(dòng)從FTP服務(wù)器下載文件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-03-03C#之關(guān)于Base64簡(jiǎn)單加密與解密方式
這篇文章主要介紹了C#之關(guān)于Base64簡(jiǎn)單加密與解密方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06