.net webapi导出html,C#(.Net Core WebAPI)之API文档的生成(Swagger)

标签:一 : 安装Swagger

搜Swashbuckle.AspNetCore

在NuGet 中,安装 Swashbuckle.AspNetCore :

fe7c82cf4363b542d9ef7787b4d51fcb.png

我使用的版本为 : 5.0.0-rc2

二 : 引入Swagger功能

Ⅰ : Startup.cs

① ,ConfigureServices方法中:

public void ConfigureServices(IServiceCollection services)

{

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonOptions(options =>

{

options.SerializerSettings.Formatting = Formatting.Indented;

});

services.AddSwaggerGen(options =>

{

options.SwaggerDoc("v1", new OpenApiInfo()

{

Title = "Swagger Test UI",

Version = "v1",

Description = "Aonaufly first ASP.NET Core Web API"

});

options.CustomSchemaIds(type => type.FullName); // 解决相同类名会报错的问题

options.IncludeXmlComments(Path.Combine(Directory.GetCurrentDirectory(), "WebAPIPoco.xml")); // 标注要使用的 XML 文档

options.DescribeAllEnumsAsStrings();

});

}

②:Configure中

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)

{

if (env.IsDevelopment())

{

app.UseDeveloperExceptionPage();

}

else

{

// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

app.UseHsts();

}

//设置全局跨域

app.UseCors(builder => builder.AllowAnyOrigin());

app.UseHttpsRedirection();

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

// 在这里面可以注入

app.UseSwaggerUI(options =>

{

options.ShowExtensions();

options.ValidatorUrl(null);

options.SwaggerEndpoint("/swagger/v1/swagger.json", "Aonaufly API V1");

options.DocExpansion(DocExpansion.None);

});

app.UseMvc();

}

三 :配置设置

①,到处项目XML , 加入1591禁止警告

284936914abc10539fdc49df1e8b80a7.png

②,将项目XML生成路径复制到项目根路径

copy $(TargetDir)WebAPIPoco.xml $(ProjectDir)WebAPIPoco.xml

df925c1c230db4a1d4ff69dc815451cb.png

③,重置默认网页为swagger , 默认是 api/values

b8968ae8a6d8be196a556f76accc0dc1.png

四 :初始结果

363b8b531c8cd3b195dc9ac29ca90e03.png

五 : 测试

///

/// 带参数的get请求

///

///

///

/// 输入 : int

/// 输出 : string

///

///

/// ID号

/// String

/// 返回字符串

/// 如果id为空

// GET api/values/5

[HttpGet("{id}")]

[ProducesResponseType(201)]

[ProducesResponseType(400)]

public ActionResult Get(int id)

{

return "value";

}

结果:

bb9bbfe6101ec1b3ca378a5812206aaa.png

标签:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值