.NET Core和Swagger 生成 Api 文档

测试/生产环境的BUG

这里更新一下在本地调试正常,在INT/PROD上抛错,错误信息为:

/**/.xml(Swagger json file) 文件找不到,在startup 里builder 的时候抛出错误。

解决方案:

编辑.csproj文件,修改输出路径,

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> 
    <DocumentationFile>bin\$(Configuration)\$(TargetFramework)\win7-x64\ChatBotApi.XML</DocumentationFile>
</PropertyGroup> 
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> 
    <DocumentationFile>bin\$(Configuration)\$(TargetFramework)\win7-x64\ChatBotApi.XML</DocumentationFile> 
</PropertyGroup>
<Target Name="PrepublishScript" BeforeTargets="PrepareForPublish"> 
    <ItemGroup> 
        <DocFile Include="bin\$(Platform)\$(Configuration)\$(TargetFramework)\win7-x64\*.xml" /> 
   </ItemGroup> 
   <Copy SourceFiles="@(DocFile)" DestinationFolder="$(PublishDir)" SkipUnchangedFiles="false" />
</Target>

也就是说,让环境自己选择环境变量,保证local/Int/Prod的输出路径都是对的,这样就可以将.xml文件根据环境注入到swagger中。

前言

最近写了好多Web api, 说太乱了,要整理一下,使用Swagger方式生成对应的api说明文档。
花了半天的时间,在这里记录和分享一些过程和遇到的问题。

遇到的主要问题:
1.localhost:9040/swagger/ not found

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

1.引用

这里引用了三个库,都是在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"

2.打开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");
        });
}

3.设置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)
{
}

4.运行结果

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

返回Json文档:

用json viewer打开json文件:

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

到此说明配置Swagger成功。

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

5.主要问题的解决办法

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

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

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

6.可以自定义UI

这个暂时没有做,今天太晚了,占个位置~

参考文档

1.Get started with Swashbuckle and ASP.NET Core
2.Swagger .NETCORE can't read json
3.ASP.NET Core 中文文档

posted @ 2018-05-29 10:10  肖恩部落  阅读(10541)  评论(30编辑  收藏  举报