.Net Core WebApi

来源:https://www.cnblogs.com/qfccc/archive/2023/08/08/17615157.html
-Advertisement-
Play Games

[toc] # MiniMalAPi - 最小的api, 請求都寫在Program.cs中, 可以做微服務 ## Demo ### Program.cs ```c# //基本請求 app.MapGet("/GetTest", () => new { result = "123", code = 20 ...


目錄

MiniMalAPi

  • 最小的api, 請求都寫在Program.cs中, 可以做微服務

Demo

Program.cs

//基本請求
app.MapGet("/GetTest", () => new { result = "123", code = 200 }).WithTags("General Request");
app.MapPost("/PostTest", () => new { result = "123", code = 200 }).WithTags("General Request");
app.MapPut("/PutTest", () => new { result = "123", code = 200 }).WithTags("General Request");
app.MapDelete("DeletePut", () => new { result = "123", code = 200 }).WithTags("General Request");

//註入
app.MapGet("/GetTestIoc", (IStudent student,IWrite pen) => student.Calligraphy(pen)).WithTags("Ioc");
app.MapGet("/GetTestIocById", (IStudent student,IWrite pen,int? id) => student.Calligraphy(pen)).WithTags("Ioc");
app.MapPost("/GetTestIocByObject", (IStudent student,IWrite pen,Result result) => student.Calligraphy(pen)).WithTags("Ioc");

Swagger

文檔+信息

Program.cs

builder.Services.AddSwaggerGen(setup =>
{
    setup.SwaggerDoc("V1", new()
    {
        Title = "qfccc",
        Version = "V1",
        Description = "qfccc description",
    });
});

app.UseSwaggerUI(setup =>
{
    setup.SwaggerEndpoint("/swagger/V1/swagger.json", "V1");
});

API版本控制

  • 該例子僅供參考

ApiVersion.cs

namespace WebApiDemo.VersionControl
{
    public class ApiVersion
    {
        public static string? Version1;
        public static string? Version2;
        public static string? Version3;
        public static string? Version4;
        public static string? Version5;
    }
}

Version1Controller.cs

  • 這裡其他版本api 修改ApiVersion.Version1即可
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApiDemo.VersionControl;

namespace WebApiDemo.Controllers
{
    [ApiExplorerSettings(GroupName = nameof(ApiVersion.Version1))]
    [Route($"api/[controller]/[action]/api.{nameof(ApiVersion.Version1)}")]
    [ApiController]
    public class Version1Controller : ControllerBase
    {

        [HttpGet]
        public IActionResult GetString() => new JsonResult(new { result = "Success" });

        [HttpPost]
        public IActionResult PostString() => new JsonResult(new { result = "Success" });

        [HttpPut]
        public IActionResult PutString() => new JsonResult(new { result = "Success" });

        [HttpDelete]
        public IActionResult DeleteString() => new JsonResult(new { result = "Success" });
    }
}

Program.cs

builder.Services.AddSwaggerGen(setup =>
{
    foreach (var field in typeof(ApiVersion).GetFields())
    {
        setup.SwaggerDoc(field.Name, new()
        {
            Title = "qfccc",
            Version = field.Name,
            Description = $"qfccc api {field.Name}",
        });
    }
});

app.UseSwaggerUI(setup =>
{
    foreach (var field in typeof(ApiVersion).GetFields())
    { 
        setup.SwaggerEndpoint($"/swagger/{field.Name}/swagger.json", field.Name);
    }
});

生成註釋

  1. 項目點擊右鍵 -> 屬性 -> 輸出 -> 勾選(文檔文件)
  2. 在AddSwaggerGen中間件添加下方代碼
string? basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
if(basePath is not null)
{
    string apiPath = Path.Combine(basePath, "項目名稱.xml");
    setup.IncludeXmlComments(apiPath);
}

解決跨域

  1. 調用方調用自己後臺,然後用後臺請求目標介面解決跨域
  2. 伺服器支持跨域請求
    • 在Action中添加這行代碼:
    • HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
  3. 使用ActionFilter 實現過濾器,代碼與上方一致, 然後在Program.cs 文件中全局註冊一下該過濾器,但是不支持Post,Put,Delete這種請求
  4. 所有請求都支持跨域可以在Program.cs中增加下方代碼:
builder.Services.AddCors( setup =>
{
    setup.AddPolicy("SolveCrossOrigin", policy =>
    {
        policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
    });
});


app.UseCors("SolveCrossOrigin");

.Net 後臺請求封裝

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace NET5WebApplication.Utility
{
    public static class HttpClientHelper
    {
        /// <summary>
        /// 發起POST同步請求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息頭</param>
        /// <returns></returns>
        public static string HttpPost(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";
            using (HttpClient client = new System.Net.Http.HttpClient())
            {
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
                {
                    if (contentType != null)
                        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
                    HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
                    return response.Content.ReadAsStringAsync().Result;
                }
            }
        }

        /// <summary>
        /// 發起POST非同步請求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息頭</param>
        /// <returns></returns>
        public static async Task<string> HttpPostAsync(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";
            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                client.Timeout = new TimeSpan(0, 0, timeOut);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
                {
                    if (contentType != null)
                        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                    HttpResponseMessage response = await client.PostAsync(url, httpContent);
                    return await response.Content.ReadAsStringAsync();
                }
            }
        }

        /// <summary>
        /// 發起GET同步請求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string HttpGet(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            using (HttpClient client = new HttpClient())
            {
                if (contentType != null)
                    client.DefaultRequestHeaders.Add("ContentType", contentType);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                HttpResponseMessage response = client.GetAsync(url).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }

        /// <summary>
        /// 發起GET非同步請求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static async Task<string> HttpGetAsync(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                if (contentType != null)
                    client.DefaultRequestHeaders.Add("ContentType", contentType);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                HttpResponseMessage response = await client.GetAsync(url);
                return await response.Content.ReadAsStringAsync();
            }
        }

        /// <summary>
        /// 發起POST同步請求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息頭</param>
        /// <returns></returns>
        public static T HttpPost<T>(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            return HttpPost(url, postData, contentType, timeOut, headers).ToEntity<T>();
        }

        /// <summary>
        /// 發起POST非同步請求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息頭</param>
        /// <returns></returns>
        public static async Task<T> HttpPostAsync<T>(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            var res = await HttpPostAsync(url, postData, contentType, timeOut, headers);
            return res.ToEntity<T>();
        }

        /// <summary>
        /// 發起GET同步請求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static T HttpGet<T>(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            return HttpGet(url, contentType, headers).ToEntity<T>();
        }

        /// <summary>
        /// 發起GET非同步請求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static async Task<T> HttpGetAsync<T>(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            var res = await HttpGetAsync(url, contentType, headers);
            return res.ToEntity<T>();
        }
    }

    public static class HttpExtension
    {
        /// <summary>
        /// 發起GET同步請求
        /// </summary>
        /// <param name="client"></param>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string HttpGet(this System.Net.Http.HttpClient client, string url, string contentType = "application/json",
                                     Dictionary<string, string> headers = null)
        {
            if (contentType != null)
                client.DefaultRequestHeaders.Add("ContentType", contentType);
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            HttpResponseMessage response = client.GetAsync(url).Result;
            return response.Content.ReadAsStringAsync().Result;
        }

        /// <summary>
        /// 發起GET非同步請求
        /// </summary>
        /// <param name="client"></param>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static async Task<string> HttpGetAsync(this System.Net.Http.HttpClient client, string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            if (contentType != null)
                client.DefaultRequestHeaders.Add("ContentType", contentType);
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            HttpResponseMessage response = await client.GetAsync(url);
            return await response.Content.ReadAsStringAsync();
        }

        /// <summary>
        /// 發起POST同步請求
        /// </summary>
        /// <param name="client"></param>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="timeOut"></param>
        /// <param name="headers">填充消息頭</param>
        /// <returns></returns>
        public static string HttpPost(this System.Net.Http.HttpClient client, string url, string postData = null,
                                      string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
            {
                if (contentType != null)
                    httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }

        /// <summary>
        /// 發起POST非同步請求
        /// </summary>
        /// <param name="client"></param>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息頭</param>
        /// <returns></returns>
        public static async Task<string> HttpPostAsync(this System.Net.Http.HttpClient client, string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";
            client.Timeout = new TimeSpan(0, 0, timeOut);
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
            {
                if (contentType != null)
                    httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                HttpResponseMessage response = await client.PostAsync(url, httpContent);
                return await response.Content.ReadAsStringAsync();
            }
        }

        /// <summary>
        /// 發起POST同步請求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息頭</param>
        /// <returns></returns>
        public static T HttpPost<T>(this System.Net.Http.HttpClient client, string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            return client.HttpPost(url, postData, contentType, timeOut, headers).ToEntity<T>();
        }

        /// <summary>
        /// 發起POST非同步請求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息頭</param>
        /// <returns></returns>
        public static async Task<T> HttpPostAsync<T>(this System.Net.Http.HttpClient client, string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            var res = await client.HttpPostAsync(url, postData, contentType, timeOut, headers);
            return res.ToEntity<T>();
        }

        /// <summary>
        /// 發起GET同步請求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static T HttpGet<T>(this System.Net.Http.HttpClient client, string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            return client.HttpGet(url, contentType, headers).ToEntity<T>();
        }

        /// <summary>
        /// 發起GET非同步請求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static async Task<T> HttpGetAsync<T>(this System.Net.Http.HttpClient client, string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            var res = await client.HttpGetAsync(url, contentType, headers);
            return res.ToEntity<T>();
        }
    }

    public static class JsonExtends
    {
        public static T ToEntity<T>(this string val)
        {
            return JsonConvert.DeserializeObject<T>(val);
        }
        public static string ToJson<T>(this T entity, Formatting formatting = Formatting.None)
        {
            return JsonConvert.SerializeObject(entity, formatting);
        }
    }
}

返回數據壓縮

  • 在Program.cs中添加下麵代碼

預設壓縮

builder.Services.AddResponseCompression();
app.UseResponseCompression();

Gzip壓縮

builder.Services.AddResponseCompression(config =>
{
    config.Providers.Add<GzipCompressionProvider>();
});

builder.Services.Configure<GzipCompressionProviderOptions>(config =>
{
    config.Level = CompressionLevel.SmallestSize;
});

緩存

介面緩存

  • 使用特性或者直接在返回頭中添加Cache-Control效果一樣
[HttpGet]
[ResponseCache(Duration = 600)]
public IActionResult GetString() => new JsonResult(new { result = "Success" });

[HttpGet]
public IActionResult GetStringEx() 
{
    HttpContext.Response.Headers.Add("Cache-Control", "public,max-age=600");
    return new JsonResult(new { result = "Success" });
}

靜態文件緩存

app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse = Prepare =>
    {
        Prepare.Context.Response.Headers.Add(HeaderNames.CacheControl, "public,max-age=600");
    }
}); 

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • QT性能優化之QT6框架高性能模型視圖代理框架千萬級數據表分頁查詢優化 簡介 本文介紹了QT模型視圖代理框架中的QT表格控制項和QT資料庫模塊中的QT資料庫查詢模型結合使用的一個應用實踐案例:QT高性能表格控制項分頁展示千萬行數據。本文介紹了這個應用實踐案例的運行效果和源代碼。這個應用實踐案例實測運行表 ...
  • ## 教程簡介 PDFBox是一個開源Java庫,支持PDF文檔的開發和轉換.使用此庫,您可以開發用於創建,轉換和操作PDF文檔的Java程式.除此之外,PDFBox還包括一個命令行實用程式,用於使用可用的PDF對PDF執行各種操作Jar文件. [PDFBox入門教程](https://www.it ...
  • 本文從源碼層面介紹了Spring如何創建bean、如何解決迴圈依賴,同時也介紹了不能解決哪些迴圈依賴,同時在文章的最後解決迴圈依賴報錯的幾個方法 ...
  • 作者:樹洞君 \ 鏈接:https://juejin.cn/post/7064376361334358046 # 事故描述 從6點32分開始少量用戶訪問app時會出現首頁訪問異常,到7點20分首頁服務大規模不可用,7點36分問題解決。 # 整體經過 6:58 發現報警,同時發現群里反饋首頁出現網路繁 ...
  • ## 一. 時間複雜度 - 時間複雜度簡單的說就是一個程式運行所消耗的時間,叫做時間複雜度,我們無法目測一個程式具體的時間複雜度,但是我們可以估計大概的時間複雜度。 - 一段好的代碼的就根據演算法的時間複雜度,即使在大量數據下也能保持高效的運行速率,這也是我們學習演算法的必要性。 ### 1.1 大O表 ...
  • ### 寫在前面 也許現在的你需要用PB完成畢業設計、需要維護遠古時代的代碼,又或者是你呆的公司就是要求要用PB開發項目。 不管你是出於什麼原因還在使用PB,不可否認PB在數據視窗非常優秀,熟練使用之後開發資料庫相關的應用非常高效 但由於PB這一框架出現得比較早,而且主要用於傳統基於資料庫得CS開發 ...
  • # UnityStats 屬性詳解 UnityStats 是 Unity 引擎提供的一個用於監測游戲性能的工具,它提供了一系列的屬性值,可以幫助開發者解游戲的運行情況,從而進行優化。本文將詳細介紹 UnityStats 的每個屬性值,並提供多個使用例子幫助開發者更好地使用 UnityStats。 # ...
  • 根據客戶需求,要在TreeView目錄樹上顯示10萬+個節點,但是目錄樹顯示10萬加節點後,整個頁面操作起來非常卡,所以給目錄樹增加了虛擬化設置。但是虛擬化設置一直沒生效,後來經過排查發現是使用的自定義滾動條導致了虛擬化設置沒有生效,後來自己寫了一個滾動條樣式,問題解決了。 目錄樹虛擬化設置屬性 W ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...