使用Swashbuckle生成简单的Swagger



我需要为另一个项目创建一些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>();
});
}

启动.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!

为什么不起作用?

我想你也需要services.AddMvcCore()。。。

最新更新