swagger+net6使用

1.屏蔽launchSettings.json文件里面的launchUrl和applicationUrl配置

如下图

2.在program类中注入swagger

builder.Services.AddSwaggerGen(options =>
{
});

添加swagger中间件

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.RoutePrefix = "";
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1"); //第二个参数可自定义命名
});

代码SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1"); 中的路径可以根据自己需要修改

以上代码就可使用swagger,如果想要方法有注释需要在第一步

builder.Services.AddSwaggerGen(options =>
{
});中加代码var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));

 

Program中所有代码
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddControllersWithViews();

builder.Services.AddSwaggerGen(options =>
{
    var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
builder.Services.AddDbContext<MoviesDbContext>(
    options =>
    {
        options.UseMySql(builder.Configuration.GetConnectionString("DefaultConnection"), new MySqlServerVersion(new Version(8, 0, 2)));
    });

var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.RoutePrefix = "";
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1"); //第二个参数可自定义命名
});

app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

 

这样swagger带注释功能就可以用了

 

posted @ 2023-08-30 17:44  二二姐  阅读(125)  评论(0编辑  收藏  举报