// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = null; }); var config = Configuration.GetSection("Connection"); services.AddDbContext <A35MgeDbContext>(options => options.UseMySql(config?.Value ?? string.Empty, mysql => { var builder = mysql .MigrationsAssembly(System.Reflection.Assembly.Load("A35Mge.MySqlDatabase").FullName) .EnableRetryOnFailure(3, TimeSpan.FromSeconds(10), null); })); services.AddIdentityServer(options => { //可以通过此设置来指定登录路径,默认的登陆路径是/account/login options.UserInteraction.LoginUrl = "/Account/Login"; options.Events.RaiseErrorEvents = true; options.Events.RaiseInformationEvents = true; options.Events.RaiseFailureEvents = true; options.Events.RaiseSuccessEvents = true; // see https://identityserver4.readthedocs.io/en/latest/topics/resources.html options.EmitStaticAudienceClaim = true; }) //添加证书加密方式,执行该方法,会先判断tempkey.rsa证书文件是否存在,如果不存在的话,就创建一个新的tempkey.rsa证书文件,如果存在的话,就使用此证书文件。 .AddDeveloperSigningCredential() //把受保护的Api资源添加到内存中 .AddInMemoryApiResources(IdsConfig.GetApiResources()) //身份信息资源 .AddInMemoryIdentityResources(IdsConfig.GetIdentityResources()) //添加自定义客户端 .AddClientStore <ClientStore>() //添加自定义账号密码的方法 .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>() //新增微信认证登陆的方法 //.AddExtensionGrantValidator<WechatLoginValidator>() .AddInMemoryApiScopes(IdsConfig.ApiScopes); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddNewtonsoftJson();// 支持 NewtonsoftJson //services.AddMvcCore(options => { // options.Filters.Add(typeof(ApiDataFilter)); // by type // //options.Filters.Add(new ApiDataFilter()); // an instance //}); //services.AddMvcCore() //.AddAuthorization(); //缓存 services.AddMemoryCache(); //使用session services.AddSession(); #region Ids 授权管理配置 这个方法放在 在ids授权之前 services.AddIdentityServer(options => { options.PublicOrigin = Appsettings.GetSectionValue("AppSettings:IdSHttpsUrl"); }) .AddDeveloperSigningCredential() .AddInMemoryIdentityResources(IdsConfig.GetIdentityResources()) .AddInMemoryApiResources(IdsConfig.GetApis()) .AddInMemoryClients(IdsConfig.GetClients()) .AddTestUsers(IdsConfig.GetUsers()); //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); #endregion Ids 授权管理配置 这个方法放在 在ids授权之前 //注意这里把授权和API合并在一起了 #region 配置api调用 Ids授权 注意这个需要放到前面 services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddJwtBearer(IdentityServerAuthenticationDefaults.AuthenticationScheme, options => { //这里面需要填写域名 //var url = Configuration.GetValue<string>("URLS"); var url = Appsettings.GetSectionValue("AppSettings:IdSHttpsUrl"); options.Authority = url; options.RequireHttpsMetadata = false; options.Audience = "api1"; //指定只使用哪个作用域,不填又前端控制 }); #endregion 配置api调用 Ids授权 注意这个需要放到前面 #region 配置跨域 services.AddCors(options => options.AddPolicy("Cors", builder => builder.WithOrigins(Appsettings.GetSectionValue("AppSettings:CorsIPs").Split(',')) .AllowAnyMethod().AllowAnyHeader().AllowCredentials())); //builder.WithOrigins("http://*****:*****@outlook.com" } // //}); // //option.SwaggerDoc("v2", new OpenApiInfo { Version = "v2", Title = "API V2" }); // option.DocInclusionPredicate((docName, apiDesc) => { var versions = // apiDesc.CustomAttributes() .OfType<ApiVersionAttribute>() .SelectMany(attr => attr.Versions); // return versions.Any(v => $"v{v.ToString()}" == docName); }); // // 包含文档文件 // option.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{typeof(Startup).Assembly.GetName().Name}.xml"), true); //}); // //[ApiVersion("2")] 通过这个绑定 #endregion 操作版本控制 services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" }); c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{typeof(Startup).Assembly.GetName().Name}.xml"), true); // 开启加权小锁 c.OperationFilter <AddResponseHeadersFilter>(); c.OperationFilter <AppendAuthorizeToSummaryOperationFilter>(); // 在header中添加token,传递到后台 c.OperationFilter <SecurityRequirementsOperationFilter>(); // 必须是 oauth2 c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"", Name = "Authorization", //jwt默认的参数名称 In = ParameterLocation.Header, //jwt默认存放Authorization信息的位置(请求头中) Type = SecuritySchemeType.ApiKey }); }); #endregion 配置swagger操作文档 services.AddHttpClient();//将HttpClient注入进来 //Senparc.CO2NET 全局注册(必须) services.AddSenparcGlobalServices(Configuration); //Senparc.Weixin 注册 services.AddSenparcWeixinServices(Configuration); //return AutofacConfigure.Register(services); //此处需要在在进行调用接口时在后面加上下划线 _ (一定要加上,后面如果有修改可以查看源码示例代码) services.AddCertHttpClient(Appsettings.GetSectionValue("SenparcWeixinSetting:TenPayV3_MchId") + "_", Appsettings.GetSectionValue("SenparcWeixinSetting:TenPayV3_MchId"), Appsettings.GetSectionValue("SenparcWeixinSetting:TenPayV3_CertPath")); //此处可以添加更多 Cert 证书 services.AddControllersWithViews(); }