The use of NSwag in the Blazor client

        OpenAPI can greatly improve development efficiency in the development of front-end and back-end separation, and the use of NSwag tools can make front-end development more automated with less code. Due to the lack of online reference resources, it is recorded here.

1. Environment

dotnet --list-sdks
5.0.403 [C:\Program Files\dotnet\sdk]
6.0.201 [C:\Program Files\dotnet\sdk]

Win10+Vs2022

2. Use NSwag to introduce OpenAPI objects in the front-end project

Open Connected Services in the front-end project under the Vs2022 solution

Select the connected service -> service reference (OpenAPI, gRPC, WCF Web Service)

 Select Add New Service

Select OpenAPI in the wizard

 

Enter the URL of the Swagger Json file

 

 After clicking Finish, the NSwag tool will automatically activate the client reference code

Click to view the generated code in the configured service, and you can see the code and classes automatically generated by the NSwag tool

//----------------------
// <auto-generated>
//     Generated using the NSwag toolchain v13.0.5.0 (NJsonSchema v10.0.22.0 (Newtonsoft.Json v11.0.0.0)) (http://NSwag.org)
// </auto-generated>
//----------------------

#pragma warning disable 108 // Disable "CS0108 '{derivedDto}.ToJson()' hides inherited member '{dtoBase}.ToJson()'. Use the new keyword if hiding was intended."
#pragma warning disable 114 // Disable "CS0114 '{derivedDto}.RaisePropertyChanged(String)' hides inherited member 'dtoBase.RaisePropertyChanged(String)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword."
#pragma warning disable 472 // Disable "CS0472 The result of the expression is always 'false' since a value of type 'Int32' is never equal to 'null' of type 'Int32?'
#pragma warning disable 1573 // Disable "CS1573 Parameter '...' has no matching param tag in the XML comment for ...
#pragma warning disable 1591 // Disable "CS1591 Missing XML comment for publicly visible type or member ..."

namespace FrontWeb
{
    [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.0.5.0 (NJsonSchema v10.0.22.0 (Newtonsoft.Json v11.0.0.0))")]
    public partial class swaggerClient 
    {
        private string _baseUrl = "";
        private System.Net.Http.HttpClient _httpClient;
        private System.Lazy<Newtonsoft.Json.JsonSerializerSettings> _settings;
    
        public swaggerClient(string baseUrl, System.Net.Http.HttpClient httpClient)
        {

 3. Use the generated code to implement calls to OpenAPI

As can be seen from the generated code, the NSwag tool automatically generates a swaggerClient class, under which each instance and API of the OpenAPI backend are implemented and can be called directly

 

@code {
    private ICollection<FrontWeb.Stock>? stocks;
    private int tt=0;
    private FrontWeb.Stock newStock = new FrontWeb.Stock();
    //读取全部记录
    protected override async Task OnInitializedAsync()
    {
        var httpclient = new HttpClient();
        var swaggerC = new swaggerClient("https://localhost:7270",httpclient);
        stocks = await swaggerC.StocksAllAsync();
        if(stocks !=null)
        {
            tt = stocks.Count;
        }
    }
    //添加一个实体
    private void addStock()
    {
        if(string.IsNullOrEmpty(newStock.CodeNum))
        {
            return;
        }
        if (newStock.CodeNum.Trim().Length >= 5)
        {
            var httpclient = new HttpClient();
            var swaggerC = new swaggerClient("https://localhost:7270", httpclient);

            swaggerC.StocksAsync(newStock);
            if (stocks != null)
            {
                stocks.Add(newStock);
            }
        }

    }
    //删除一个实体
    private void  deleteStock(FrontWeb.Stock tmpStock)
    {
        if(tmpStock !=null)
        {
            var httpclient = new HttpClient();
            var swaggerC = new swaggerClient("https://localhost:7270", httpclient);

            swaggerC.Stocks4Async(tmpStock.StockId);

            stocks.Remove(tmpStock);

        }
    }

4. Reference articles

1. Getting started with NSwag and ASP.NET Core | Microsoft Docs

2. Getting started with Swashbuckle and ASP.NET Core | Microsoft Docs

Guess you like

Origin blog.csdn.net/zhujisoft/article/details/125866450