1 Star 0 Fork 0

程文龙47/Cwl_VoteSys

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Startup.cs 5.69 KB
一键复制 编辑 原始数据 按行查看 历史
程文龙47 提交于 2024-06-24 20:12 . 添加项目文件。
using Cwl_VoteSys.Models;
using Cwl_VoteSys.Models.Database;
using Cwl_VoteSys.Service;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Cwl_VoteSys
{
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();
services.AddDbContext<Cwl_VoteSysContext>();
services.Configure<JWTConfig>(Configuration.GetSection("JWTConfig"));
var tokenConfigs = Configuration.GetSection("JWTConfig").Get<JWTConfig>();
//添加cors
services.AddCors(options =>
{
//添加core 策略
options.AddPolicy("Policy1", //策略名
builder =>
{
builder.WithOrigins("*") //表示可以被所有地址跨域访问 允许跨域访问的地址,不能以正反斜杠结尾。
.SetIsOriginAllowedToAllowWildcardSubdomains()//设置策略里的域名允许通配符匹配,但是不包括空。
//例:http://localhost:3001 不会被通过
// http://xxx.localhost:3001 可以通过
.AllowAnyHeader()//配置请求头
.AllowAnyMethod();//配置允许任何 HTTP 方法访问
});
});
//添加swagger
services.AddSwaggerGen(options =>
{
options.CustomSchemaIds(x => x.FullName);
options.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
// 获取xml文件名
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
// 获取xml文件路径
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
// 添加控制器层注释,true表示显示控制器注释
options.IncludeXmlComments(xmlPath, true);
//添加授权的入口
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Description = "在下框中输入请求头中需要添加Jwt授权Token:Bearer Token",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme{
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"}
},new string[] { }
}
});
});
//Authentication
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.UTF8.GetBytes(tokenConfigs.Secret)),
ValidIssuer = tokenConfigs.Issuer,
ValidAudience = tokenConfigs.Audience,
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddScoped<IJWTService, JWTService>();
}
// 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.UseAuthentication();//启用认证
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "coreMVC3.1");
//c.RoutePrefix = string.Empty;
c.RoutePrefix = "API"; //如果是为空 访问路径就为 根域名/index.html,注意localhost:端口号/swagger是访问不到的
//路径配置,设置为空,表示直接在根域名(localhost:8001)访问该文件
// c.RoutePrefix = "swagger"; // 如果你想换一个路径,直接写名字即可,比如直接写c.RoutePrefix = "swagger"; 则访问路径为 根域名/swagger/index.html
});
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/cheng-wenlong-47/cwl_-vote-sys.git
git@gitee.com:cheng-wenlong-47/cwl_-vote-sys.git
cheng-wenlong-47
cwl_-vote-sys
Cwl_VoteSys
master

搜索帮助