【发布时间】:2020-10-30 03:58:22
【问题描述】:
我需要为另一个项目创建一些 Swagger 文档,所以我想用 Swashbuckle 快速完成它以节省一些时间。在 Visual Studio 中,我使用 ASP.NET Core WEB 应用程序创建了一个新项目,并选择了模型-视图-控制器模板。然后我通过 Nuget 安装了 Swashbuckle 并将模板值更改为:
程序.cs
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Startup.cs
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
.AddControllers()
.AddJsonOptions(x =>
{
x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
x.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
x.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
});
services.AddSwaggerGen(x =>
{
x.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
x.DescribeAllParametersInCamelCase();
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
x.IncludeXmlComments(xmlPath);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger(x => x.SerializeAsV2 = true);
app.UseSwaggerUI(x =>
{
x.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1");
x.RoutePrefix = string.Empty;
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
控制器/ApiController.cs
[ApiController]
[Produces("application/json")]
[Consumes("application/json")]
[Route("api/MyApi/v1/")]
public class ApiController : Controller
{
/// <summary>
/// Gets something as bytes for the given <paramref Id="id"/>.
/// </summary>
/// <returns>A result object indicating success or failure.</returns>
/// <response code="200">The request succeeded.</response>
/// <response code="400">
/// At least one of the following issues occurred:
/// - Error
/// </response>
/// <response code="500">An unexpected error occurred.</response>
[HttpGet("{id}")]
public static Task<Result> GetSomething(string id)
{
return new Task<Result>(null, "");
}
}
现在,当我启动 API 并看到招摇时,我得到了“我的 API”名称,但没有端点:
No operations defined in spec!
为什么这不起作用?
【问题讨论】:
标签: c# swagger swashbuckle