Мне нужно было создать несколько документов Swagger для другого проекта, поэтому я хотел быстро сделать это с помощью Swashbuckle, чтобы сэкономить время. В Visual Studio я создал новый проект с ASP. NET Core WEb Application и выбрал шаблон Model-View-Controller. Затем я установил Swashbuckle через Nuget и изменил значения шаблона на следующие:
Program.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();
});
}
}
Controllers / 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!
Почему это не работает?