1、新建项目,目标框架选 .NET Core 3.1,新建出一个解决方案
2、安装 Swashbuckle.AspNetCore包 工具->NuGet包管理器->解决方案管理包,浏览输入Swashbuckle.AspNetCore,进行安装
3、打开项目下的 Startup.cs
在 ConfigureServices方法 和 Configure方法进行如下配置,缺失的相关引用,根据提示在NuGet包管理器里进行安装,然后引用
public class Startup
{
private IApiVersionDescriptionProvider provider;
private readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
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();
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder => builder.AllowAnyOrigin().AllowAnyHeader()
.WithMethods("GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS")
);
});
services.AddApiVersioning(option =>
{
// 可选,为true时API返回支持的版本信息
option.ReportApiVersions = true;
// 不提供版本时,默认为1.0
option.AssumeDefaultVersionWhenUnspecified = true;
// 请求中未指定版本时默认为1.0
option.DefaultApiVersion = new ApiVersion(1, 0);
option.ApiVersionReader = new HeaderApiVersionReader("apiVersion");
}).AddVersionedApiExplorer(option =>
{
// 版本名的格式:v+版本号
option.GroupNameFormat = "'v'V";
//option.AssumeDefaultVersionWhenUnspecified = true;
});
this.provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();
// 注册Swagger服务
services.AddSwaggerGen(c =>
{
// 多版本控制
foreach (var item in provider.ApiVersionDescriptions)
{
// 添加文档信息
c.SwaggerDoc(item.GroupName, new OpenApiInfo
{
Title = "CoreWebApi",
Version = item.ApiVersion.ToString(),
Description = "ASP.NET CORE WebApi",
Contact = new OpenApiContact
{
Name = "Stella",
Email = "123@qq.com",
}
});
}
// 使用反射获取xml文件。并构造出文件的路径
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
// 启用xml注释. 该方法第二个参数启用控制器的注释,默认为false.
c.IncludeXmlComments(xmlPath, true);
#region 启用swagger验证功能
添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称一致即可,CoreAPI。
//var security = new Dictionary<string, IEnumerable<string>> { { "CoreAPI", new string[] { } }, };
//c.AddSecurityRequirement(security);
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT授权(数据将在请求头中进行传输) 在下方输入Bearer {token} 即可",
Name = "Authorization",//jwt默认的参数名称
In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme{
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"}
},new string[] { }
}
});
#endregion 启用swagger验证功能
});
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("123456111111111111111111")),//token.Secret)),
ValidIssuer = "webapi.cn",//token.Issuer,
ValidAudience = "WebApi",//token.Audience,
ValidateIssuer = true,
ValidateAudience = true
};
});
//解决Multipart body length limit 134217728 exceeded
services.Configure<FormOptions>(x =>
{
x.ValueLengthLimit = int.MaxValue;
x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart
});
}
// 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();
app.UseSwaggerUI(c =>
{
//c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Demo v1");
foreach (var item in provider.ApiVersionDescriptions)
{
//c.SwaggerEndpoint("/swagger/v1/swagger.json", "CoreAPI"); 单版本
c.SwaggerEndpoint($"/swagger/{item.GroupName}/swagger.json", "CoreAPI : " + item.ApiVersion);
}
c.RoutePrefix = string.Empty;
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers(); //这里有改动
});
}
}
4、
项目右击打开 ->属性
应用程序->启动对象可以设置一下
生成-> a.取消显示警告,如果不写注释会报警,可以加1591,不加则方法加注释就好了
b.启用XML文档
调试–>a.启动浏览器 b.JavaScript诊断组件可选可不选 c.url设置一下
5、运行,默认版本1.0,没有接口
6、写一个API测试一下