Install-Package Swashbuckle.AspNetCore
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace CoreTest
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//1、注册服务Swagger
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
{
Version = "v1",
Title = "My API",
Description = "by JiaJia"
});
});
}
// 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
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
//2、添加到管道
#if DEBUG
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
// c.DocExpansion(DocExpansion.None);
});
#endif
}
}
}
http://localhost:60238/swagger/index.html
ConfigureServices
方法中的 AddSwaggerGen
处增加 IncludeXmlComments
处理。//1、注册服务Swagger
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
{
Version = "v1",
Title = "My API",
Description = "by JiaJia"
});
//在 Start.cs => ConfigureServices 方法中的 AddSwaggerGen 处增加 IncludeXmlComments 处理。
options.IncludeXmlComments(string.Format("{0}/CoreTest.xml",
AppDomain.CurrentDomain.BaseDirectory));
/\*或者这种添加方式//为 Swagger JSON and UI设置xml文档注释路径
var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
var xmlPath = Path.Combine(basePath, "CoreTest.xml");//和项目名对应
options.IncludeXmlComments(xmlPath);\*/
});
///
/// 用户ID
///
[HttpGet("{id}")]
public ActionResult
{
return "user info";
}
即
Install-Package MiniProfiler.AspNetCore.Mvc
//注册服务MiniProfiler
services.AddMiniProfiler(options =>
{
options.RouteBasePath = "/profiler";//注意这个路径要和下边 index.html 脚本配置中的一致,
(options.Storage as MemoryCacheStorage).CacheDuration = TimeSpan.FromMinutes();
});
//调用MiniProfiler中间件
app.UseMiniProfiler();
当前这个时候还不能使用,我们还需要在 Swagger 中进行配置,以便它能在 swagger 中使用。
上边我们在配置中已经启动了服务,接下来就需要设置如何在 swagger 中展示了,这个时候我们就需要自定义我们的swagger主页了,以前我们是用的默认的index.html,现在咱们需要自定义一个:
从官网 Github 上,下载最新的 index.html:https://github.com/swagger-api/swagger-ui/blob/master/dist/index.html