欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

c#代碼生成URL地址的示例

 更新時間:2021年04月12日 08:27:23   作者:超然  
這篇文章主要介紹了c#代碼生成URL地址的方法,幫助大家更好的理解和學習使用c#,感興趣的朋友可以了解下

“頭疼”

自己在用Angular做項目時,前端要請求后端數(shù)據(jù)時的代碼如下

this.http.get("url/xxx")

這是請求一個URL地址數(shù)據(jù)最簡單的代碼,但是如此簡單的代碼還會遇到一些頭疼的問題

  • URL地址拼寫錯誤,有可能折騰半天才發(fā)現(xiàn)😑
  • 后端修改了地址沒通知到前端,測試不到位就炸了,不是所有項目都有那么規(guī)范的接口變更流程😑
  • 查看代碼的時候,看著URL地址,這個地址用途是哈?還要翻接口文檔😑

“吃藥”

為了解決這個問題,我們需要一個包含所有接口的文件

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`,
  },
}

那么請求代碼就可以改成

this.http.get(WebAPI.Auth.GetUser)

但是維護這個文件是件吃力的事情,作為一個時刻想著如何偷懶的程序員,吃力的事情就讓計算機去干,所以寫一個代碼生成工具。

工具代碼

    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

上面代碼大概的流程就是

  1. 利用反射讀取程序集中包含ApiControllerAttribute特性的類
  2. 利用發(fā)射讀取HttpGetAttribute、HttpPostAttribute、HttpPutAttribute、HttpDeleteAttribute特性的方法
  3. 根據(jù)需要的格式生成代碼
  4. 將代碼文件寫入ClientApp/src/app/web-api.ts

有了這個東西帶來以下好處

  1. URL地址拼寫錯誤問題,不存在的🎉
  2. 后端修改了接口,前端直接編譯不過,立即發(fā)現(xiàn)問題🎉
  3. 鼠標停留,接口注釋就顯示了🎉

以上就是c#代碼生成URL地址的方法的詳細內(nèi)容,更多關(guān)于c#代碼生成URL地址的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • WPF實現(xiàn)在線預覽和顯示W(wǎng)ord和PDF文件

    WPF實現(xiàn)在線預覽和顯示W(wǎng)ord和PDF文件

    這篇文章主要為大家詳細介紹了如何使用WPF實現(xiàn)在線預覽和顯示W(wǎng)ord和PDF文件,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2024-02-02
  • Visual Studio 中自定義代碼片段的方法

    Visual Studio 中自定義代碼片段的方法

    這篇文章主要介紹了Visual Studio 中自定義代碼片段的方法,本文分步驟通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-03-03
  • c# 常用框架匯總

    c# 常用框架匯總

    這篇文章主要介紹了c# 常用框架匯總,幫助大家更好的理解和學習使用c#,感興趣的朋友可以了解下
    2021-04-04
  • 基于C#實現(xiàn)SM2加簽驗簽工具

    基于C#實現(xiàn)SM2加簽驗簽工具

    這篇文章主要為大家詳細介紹了如何基于C#實現(xiàn)一個SM2加簽驗簽工具,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2024-10-10
  • 關(guān)于C#中async/await的用法實例詳解

    關(guān)于C#中async/await的用法實例詳解

    這篇文章主要介紹了關(guān)于C#中async/await的用法,今天寫一個demo徹底搞明白async/await的用法,代碼簡單易懂,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-02-02
  • C#中間語言及ILDASM工具用法

    C#中間語言及ILDASM工具用法

    這篇文章介紹了C#中間語言及ILDASM工具用法,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-01-01
  • C#開發(fā)windows服務實現(xiàn)自動從FTP服務器下載文件

    C#開發(fā)windows服務實現(xiàn)自動從FTP服務器下載文件

    這篇文章主要為大家詳細介紹了C#開發(fā)windows服務實現(xiàn)自動從FTP服務器下載文件,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-03-03
  • C# 委托(delegate) 的小例子

    C# 委托(delegate) 的小例子

    利用委托(delegate)好像也能解決避免大量switch case的代碼。
    2013-03-03
  • C#編程高并發(fā)的幾種處理方法詳解

    C#編程高并發(fā)的幾種處理方法詳解

    這篇文章主要為大家詳細介紹了C#編程高并發(fā)的幾種處理方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • C#之關(guān)于Base64簡單加密與解密方式

    C#之關(guān)于Base64簡單加密與解密方式

    這篇文章主要介紹了C#之關(guān)于Base64簡單加密與解密方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-06-06

最新評論