public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration configuration, IHostApplicationLifetime applicationLifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseStaticFiles();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPI_Serum v1"));
//配置允许跨域访问;
//添加时间:2021-12-17 11:15:27;
app.Use(async (context, next) =>
{
if (context.Request.Method == "OPTIONS")
{
//允许处理跨域
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Access-Control-Allow-Headers", "*");
context.Response.Headers.Add("Access-Control-Allow-Methods", "*");
await context.Response.CompleteAsync();
}
else
{
//允许处理跨域
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Access-Control-Allow-Headers", "*");
context.Response.Headers.Add("Access-Control-Allow-Methods", "*");
await next();
}
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseAuthentication();
app.Run(new RequestDelegate(async g =>
{
//根目录/设置访问内容,比如http://localhost:5000/
if (g.Request.Path == "/")
{
//方式一:自定义设置返回内容
g.Response.ContentType = "text/html;charset=utf-8";
await g.Response.WriteAsync("欢迎使用webapi<br/> <a href=\"/swagger\" target=\"_blank\">webapi接口swagger文档</a>");
//方式二:重定向url
//g.Response.Redirect("/swagger");
//await Task.CompletedTask;
}
}));
}
效果图: