亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

ASP.NET Core中使用Swagger

 更新時(shí)間:2022年03月24日 09:31:15   作者:.NET開發(fā)菜鳥  
這篇文章介紹了ASP.NET Core中使用Swagger的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

一、什么是Swagger

隨著技術(shù)的不斷方法,現(xiàn)在的網(wǎng)站開發(fā)基本都是使用前后端分離的模式,這樣使前端開發(fā)者和后端開發(fā)者只需要專注自己擅長的即可。但這種方式會存在一種問題:前后端通過API接口的方式進(jìn)行調(diào)用,接口文檔的好壞可以決定開發(fā)的進(jìn)度。以前如果使用Word的形式提供接口文檔,或多或少的都會存在各種問題。前端抱怨說后端給的接口文檔與實(shí)際情況不一致。而后端開發(fā)人員又覺得編寫以及維護(hù)接口文檔很費(fèi)精力,文檔經(jīng)常不能及時(shí)更新,導(dǎo)致前端看到的還是舊的接口文檔。這時(shí)候就需要使用Swagger了。

那么什么是Swagger呢?Swagger是最流行的API開發(fā)工具,它遵循了OpenAPI規(guī)范,可以根據(jù)API接口自動生成在線文檔,這樣就可以解決文檔更新不及時(shí)的問題。它可以貫穿于整個(gè)API生態(tài),比如API的設(shè)計(jì)、編寫API文檔等。而且Swagger還是一種通用的、與具體編程語言無關(guān)的API描述規(guī)范。

有關(guān)更多Swagger的介紹,可以參考Swagger官網(wǎng),官網(wǎng)地址:https://swagger.io/

二、ASP.NET Core中使用Swagger

這里使用最新的ASP.NET Core 3.1創(chuàng)建WebAPI接口。關(guān)于如何創(chuàng)建WebAPI這里不在描述。創(chuàng)建后的WebAPI項(xiàng)目結(jié)構(gòu)如下:

1、添加Swagger

直接在NuGet里面搜索Swashbuckle.AspNetCore包進(jìn)行安裝:

2、添加服務(wù)

在Startup類的ConfigureServices方法里面注入服務(wù):

public void ConfigureServices(IServiceCollection services)
{
    // 添加Swagger
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "API Demo", Version = "v1" });
    });
    services.AddControllers();
}

3、添加中間件

在Startup類的Configure方法里面添加Swagger有關(guān)的中間件:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    // 添加Swagger有關(guān)中間件
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Demo v1");
    });

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

4、添加控制器

新建一個(gè)控制器,里面包括基礎(chǔ)的增刪改查方法:

using Microsoft.AspNetCore.Mvc;

namespace SwaggerDemo.Controllers
{
    [Route("api/student")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "Tom";
        }

        [HttpPost]
        public void Post()
        {
            
        }

        [HttpPut]
        public void Put()
        {

        }

        [HttpDelete]
        public void Delete()
        {

        }
    }
}

運(yùn)行程序,修改一下url地址:

http://localhost:5000/swagger/index.html

如下圖所示:

這樣就可以看到接口了。但這樣還不是我們最終想要的結(jié)果,我們想知道每個(gè)方法的注釋和方法參數(shù)的注釋,這就需要對接口做XML注釋了。首先安裝Microsoft.Extensions.PlatformAbstractions包:

然后修改ConfigureServices方法,增加下面的方法:

public void ConfigureServices(IServiceCollection services)
{
    #region 添加Swagger
    services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1",new  OpenApiInfo { Title = "My API", Version = "v1" });
        // 獲取xml文件名
        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        // 獲取xml文件路徑
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        // 添加控制器層注釋,true表示顯示控制器注釋
        options.IncludeXmlComments(xmlPath, true);
    });
    #endregion
    services.AddControllers();
}

然后給新建的接口添加注釋:

using Microsoft.AspNetCore.Mvc;

namespace SwaggerDemo.Controllers
{

    /// <summary>
    /// 學(xué)生控制器
    /// </summary>
    [Route("api/student")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        /// <summary>
        /// 獲取所有學(xué)生
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string Get()
        {
            return "Tom";
        }

        /// <summary>
        /// 新增學(xué)生
        /// </summary>
        [HttpPost]
        public void Post()
        {
            
        }

        /// <summary>
        /// 修改學(xué)生信息
        /// </summary>
        [HttpPut]
        public void Put()
        {

        }

        /// <summary>
        /// 刪除學(xué)生信息
        /// </summary>
        [HttpDelete]
        public void Delete()
        {

        }
    }
}

項(xiàng)目右鍵,選擇屬性,勾選“XML文檔文件”,如下圖所示:

在運(yùn)行程序:

可以看到,剛才在控制器上面添加的注釋信息都顯示出來了。這樣前端就可以直接查看接口文檔了。

Swagger除了可以顯示接口注釋以外,還可以進(jìn)行調(diào)試,以前調(diào)試都是使用Postman,我們也可以直接使用Swagger進(jìn)行調(diào)試。新添加一個(gè)Student類:

namespace SwaggerDemo
{
    public class Student
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }
    }
}

然后新建一個(gè)集合,里面添加一些Student的數(shù)據(jù),模擬數(shù)據(jù)庫操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SwaggerDemo
{
    public class DataHelper
    {
        public static List<Student> ListStudent = new List<Student>();

        public static List<Student> GetStudent()
        {
            for (int i = 0; i < 5; i++)
            {
                Student student = new Student();
                student.ID = i;
                student.Name = $"測試_{i}";
                student.Age = 20 + i;
                ListStudent.Add(student);
            }

            return ListStudent;
        }
    }
}

然后修改Student控制器:

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace SwaggerDemo.Controllers
{

    /// <summary>
    /// 學(xué)生控制器
    /// </summary>
    [Route("api/student")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        /// <summary>
        /// 獲取所有學(xué)生
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public List<Student> Get()
        {
            return DataHelper.GetStudent();
        }

        /// <summary>
        /// 新增學(xué)生
        /// </summary>
        /// <param name="entity">學(xué)生實(shí)體</param>
        /// <returns></returns>
        [HttpPost]
        public List<Student> Post(Student entity)
        {
            DataHelper.ListStudent.Add(entity);
            return DataHelper.ListStudent;
        }

        /// <summary>
        /// 修改學(xué)生信息
        /// </summary>
        /// <param name="entity">學(xué)生實(shí)體</param>
        /// <returns></returns>
        [HttpPut]
        public List<Student> Put(Student entity)
        {
            for (int i = 0; i < DataHelper.ListStudent.Count; i++)
            {
                if (DataHelper.ListStudent[i].ID == entity.ID)
                {
                    DataHelper.ListStudent[i].Name = entity.Name;
                    DataHelper.ListStudent[i].Age = entity.Age;
                    break;
                }
            }
            return DataHelper.ListStudent;
        }

        /// <summary>
        /// 刪除學(xué)生信息
        /// </summary>
        /// <param name="id">學(xué)生Id</param>
        /// <returns></returns>
        [HttpDelete]
        public List<Student> Delete(int id)
        {
            for (int i = 0; i < DataHelper.ListStudent.Count; i++)
            {
                if(DataHelper.ListStudent[i].ID == id)
                {
                    DataHelper.ListStudent.Remove(DataHelper.ListStudent[i]);
                    break;
                }
            }
            return DataHelper.ListStudent;
        }
    }
}

運(yùn)行程序:

這時(shí)候是不能輸入的,只能查看,點(diǎn)擊右上角的“Try it out”:

這時(shí)會變成Cancel,點(diǎn)擊Cancel會回到Try it out:

我們點(diǎn)擊Execute執(zhí)行:

下面會列出執(zhí)行結(jié)果:

這樣就完成了GET方法的調(diào)試。這是無參數(shù)方法的調(diào)試,如果有參數(shù)的方法怎么調(diào)試呢?我們以POT方法為例。我們點(diǎn)開POST方法:

然后點(diǎn)擊“Tty it out”,可以變成輸入狀態(tài),輸入?yún)?shù),點(diǎn)擊“Execute”按鈕執(zhí)行:

最后在下面就會輸出結(jié)果:

PUT和DELETE可以使用同樣的方式進(jìn)行測試。

三、總結(jié)

上面簡單介紹了什么是Swagger,以及如何利用Swagger進(jìn)行調(diào)試,這樣只需要啟動程序即可,不需要在額外的使用Postman進(jìn)行測試。使用Swagger可以保持接口文檔能夠及時(shí)更新。

到此這篇關(guān)于ASP.NET Core中使用Swagger的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論