77

.NET Core和Swagger 生成 API文档

 7 years ago
source link: http://www.10tiao.com/html/337/201806/2660102139/2.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

(点击上方蓝字,可快速关注我们)


来源:庸斋杂记

cnblogs.com/shy-huang/p/9102214.html


前言


最近写了好多Web API, 要整理一下,使用Swagger。


花了半天的时间,在这里记录和分享一些过程和遇到的问题。


遇到的主要问题:


1、localhost:9040/swagger/ not found



2、http://localhost:9040/swagger界面可以打开,但是can't read json file.



一、引用


这里引用了三个库,都是在Nuget上安装:


  1. Microsoft.AspNetCore.StaticFiles, Version="2.0.3" , 这个package提供UI显示相关服务


  2. Swashbuckle.AspNetCore, Version="2.4.0"


  3. Swashbuckle.AspNetCore.SwaggerUi, Version="2.4.0"


二、打开startup.cs文件


using Swashbuckle.AspNetCore.Swagger;


在ConfigureServices集合中注入AddSwaggerGen:


public void ConfigureServices(IServiceCollection services)

{

        services.AddMvc();            

        // Enable CORS

        services.AddCors();

        //Inject Swagger 

        services.AddSwaggerGen(c =>

        {

            c.SwaggerDoc("v1", new Info { Title = "MyApi", Version = "v1" });

            // Set the comments path for the Swagger JSON and UI.

            var xmlPath = Path.Combine(AppContext.BaseDirectory, "ChatBotApi.XML");

            c.IncludeXmlComments(xmlPath);

        });

}


在Configure中启用中间件,允许Swagger提供服务生成json文档以及UI:


public void Configure(IApplicationBuilder app, IHostingEnvironment env)

{

        if (env.IsDevelopment())

        {

            app.UseDeveloperExceptionPage();

        }

        else

        {

            app.UseExceptionHandler("/Home/Error");

        }


        app.UseMvc(routes =>

        {

            routes.MapRoute(

                name: "default",

                template: "{controller}/{action=Index}/{id?}");

        });


        app.UseStaticFiles();


        // Enable middleware to serve generated Swagger as a JSON endpoint.

        app.UseSwagger(c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; });

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 

        // specifying the Swagger JSON endpoint.

        app.UseSwaggerUI(c =>

        {

            //c.RoutePrefix = "swagger/ui";

            c.SwaggerEndpoint("v1/swagger.json", "ChatBotApi");

        });

}


三、设置XML注释


在 Visual Studio 中右击项目并且选择 Properties 在 Output Settings 区域下面点击 XML Documentation file 。



这时候编译项目,会出现很多warning,提示api没有注释,在每个Api controller上方,连续输入三个'/',即可将api的对应信息补充完整,要给每个Api route加上 http的请求方式。

在各个Api里加上注释:


/// <summary>

/// Put value by id and value

/// </summary>

/// <param name="id">id</param>

/// <param name="value">value</param>

/// PUT api/values/5

[HttpPut("{id}")]

public void Put(int id, [FromBody]string value)

{

}

 

四、运行结果


1、在浏览器中输入:http://localhost:/swagger/v1/swagger.json


返回Json文档:



用json viewer打开json文件:



2、在浏览器输入:http://localhost:9040/swagger/



到此说明配置Swagger成功。


详细的API列表和文档说明:



五、主要问题的解决办法


1、RoutePrefix


这是个坑,要好好匹配当前的项目路径,不然UI打不开


2、SwaggerEndpoint


这是个坑,也是一样,如果路径匹配错误,UI打开了但是读取json文档失败。


这两个路径配置可以多试几次,我尝试了几十次~~


看完本文有收获?请转发分享给更多人

关注「DotNet」,提升.Net技能 

淘口令复制以下红色内容,再打开手淘即可购买

范品社,使用¥极客T恤¥抢先预览(长按复制整段文案,打开手机淘宝即可进入活动内容)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK