public void ConfigureServices(IServiceCollection services) { // HTTPS Redirect DI services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 8081; }); // EntityFramework Core DI services.AddDbContext <SolutionDbContext>(options => { options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("WebAPI.Infrastructure.Gateway")); options.EnableSensitiveDataLogging(false); }); // Repository DI services.AddScoped <IOrderRepository, OrderRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); // AutoMapper DI services.AddAutoMapper(typeof(MappingProfile)); // IUrlHelper DI services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddScoped <IUrlHelper>(x => { var actionContext = x.GetRequiredService <IActionContextAccessor>().ActionContext; var factory = x.GetRequiredService <IUrlHelperFactory>(); return(factory.GetUrlHelper(actionContext)); }); // MVC DI services.AddMvc(options => { options.ReturnHttpNotAcceptable = true; // options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); 支持XML输出 // options.InputFormatters.Add(new XmlDataContractSerializerInputFormatter(options)); 支持XML输入 // 支持自定义mediaType,其中coName为自定义的名字,一般为公司名 var outputFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); outputFormatter?.SupportedMediaTypes.Add("application/vnd.coName.hateoas+json"); var inputFormatter = options.InputFormatters.OfType <JsonInputFormatter>().FirstOrDefault(); if (inputFormatter != null) { inputFormatter.SupportedMediaTypes.Add("application/vnd.coName.order.create+json"); inputFormatter.SupportedMediaTypes.Add("application/vnd.coName.order.update+json"); } }) .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) .AddFluentValidation(); // FluentValidation DI Step1 // Property mapping DI var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <OrderPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); // Type Helper DI services.AddTransient <ITypeHelperService, TypeHelperService>(); // FluentValidation DI Step2 services.AddTransient <IValidator <OrderAddResource>, OrderAddResourceValidator>(); services.AddTransient <IValidator <OrderUpdateResource>, OrderUpdateResourceValidator>(); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc( options => { options.ReturnHttpNotAcceptable = true; //启用406状态码, 当使用Postman发送一个请求,并且将请求头里面的Accept值修改为 application/xml, 之请求xml格式的资源, 此时我们的api如果不支持xml格式就会返回406状态码, 下行代码启用xml //options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); //启用xml格式资源 //供应商自定义媒体类型 var inputFormatter = options.InputFormatters.OfType <JsonInputFormatter>().FirstOrDefault(); if (inputFormatter != null) { inputFormatter.SupportedMediaTypes.Add("application/vnd.cgzl.post.create+json"); inputFormatter.SupportedMediaTypes.Add("application/vnd.cgzl.post.update+json"); } var outputFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); if (outputFormatter != null) { outputFormatter.SupportedMediaTypes.Add("application/vnd.cgzl.hateoas+json"); } }) .AddJsonOptions( options => { //使的接口返回的json数据的 键 首字母小写的驼峰式结构 options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) //FluentValidation .AddFluentValidation(); services.AddDbContext <MyContext>(options => { options.UseSqlite("Data Source=BlogDemo.db"); }); services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 5001; }); //Scope: 每次Http请求会创建一个实例,线程内唯一对象 //Transient: 每次其他的类请求(不是指HTTP Request)都会创建一个新实例,它比较适合轻量级的无状态的(Stateless)的service. //Singleton: 在第一次创建的时候就会创建一个实例, 以后也只有这一个实例; 或者在ConfigureServices这段代码的时候创建唯一一个实例 services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); //将创建的 MappingProfile 放到依赖注入容器中 services.AddAutoMapper(typeof(Startup)); // FluentValidation 第三方验证 services.AddTransient <IValidator <PostAddResource>, PostAddOrUpdateResourceValidator <PostAddResource> >(); services.AddTransient <IValidator <PostUpdateResource>, PostAddOrUpdateResourceValidator <PostUpdateResource> >(); //使用IUrlHelper,生成前一夜后一页uri services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddScoped <IUrlHelper>( factory => { var actionContext = factory.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); //注册 IPropertyMappingContainer var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <PostPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); //注册ITypeHelperService,某个类型的属性中是否包含了传过来的所有字段 services.AddTransient <ITypeHelperService, TypeHelperService>(); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { //配置内容协商不成功时返回406 options.ReturnHttpNotAcceptable = true; //配置内容协商使服务器返回资源支持xml格式 //options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); //配置core使用自定义的媒体类型作为传入数据 var inputFormatter = options.InputFormatters.OfType <JsonInputFormatter>().FirstOrDefault(); if (inputFormatter != null) { inputFormatter.SupportedMediaTypes.Add("application/vnd.smallprogram.post.create+json"); inputFormatter.SupportedMediaTypes.Add("application/vnd.smallprogram.post.update+json"); } //配置core使用自定义的媒体类型返回数据 var outputFormatters = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); if (outputFormatters != null) { outputFormatters.SupportedMediaTypes.Add("application/vnd.smallprogram.hateoas+json"); } //options.InputFormatters.Add(new XmlDataContractSerializerInputFormatter()); }) .AddJsonOptions(options => { //设置返回的Json中属性名称为小写字母 options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) .AddFluentValidation();//配置Asp.net Core启用FluentValidation验证 //获取当前机器名称 var MachineName = System.Environment.MachineName; var ConnectionsString = ""; if (MachineName == "CGYYPC") //如果时单位机器 { ConnectionsString = configuration.GetConnectionString("CgyyConnection"); //ConnectionsString = configuration["ConnectionStrings:CgyyConnection"]; } else { ConnectionsString = configuration.GetConnectionString("HomeConnection"); //ConnectionsString = configuration["ConnectionStrings:HomeConnection"]; } services.AddDbContext <MyContext>(options => { options.UseSqlServer(ConnectionsString); }); //https重定向 services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 6001; }); //注册Respository services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IPostImageRepository, PostImageRepository>(); //注册UnitOfWork services.AddScoped <IUnitOfWork, UnitOfWork>(); //注册映射服务 services.AddAutoMapper(); //注册FluentValidat验证器 services.AddTransient <IValidator <PostAddResource>, PostAddOrUpdateResourceValidator <PostAddResource> >(); services.AddTransient <IValidator <PostUpdateResource>, PostAddOrUpdateResourceValidator <PostUpdateResource> >(); services.AddTransient <IValidator <PostImageResource>, PostImageResourceValidator>(); //注册配置URI Helper services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); //单例的ActionContextAccessor依赖注入 services.AddScoped <IUrlHelper>(factory => { var actionContext = factory.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); //注册配置Resource到Entity的映射,用于排序使用 var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <PostPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); //注册配置ResourceModel塑形属性合法性判断服务 services.AddTransient <ITypeHelperService, TypeHelperService>(); #region 配置IdentityServer4的AccessToken验证 services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = "https://localhost:5001"; //授权地址配置为Idp的地址 options.ApiName = "RESTApi"; //授权ApiName配置为Idp中配置的Scopes里的ApiName }); #endregion //配置允许跨域请求 services.AddCors(options => { options.AddPolicy("AllowAngularDevOrigin", builder => builder.WithOrigins("http://localhost:4200") .WithExposedHeaders("X-Pagination") //允许自定义header .AllowAnyHeader() .AllowAnyMethod()); }); #region 配置所有控制器访问策略 services.Configure <MvcOptions>(options => { //配置跨域过滤器 options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAngularDevOrigin")); //配置策略,所有控制器只有经过身份验证的用户可以访问 var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); //添加策略 options.Filters.Add(new AuthorizeFilter(policy)); }); #endregion }
//服务注册 public void ConfigureServices(IServiceCollection services) { services.AddMvc( options => { options.ReturnHttpNotAcceptable = true; //客户端返回类型开启校验,.net core默认是Json格式 //options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); //接受xml格式的数据 var intputFormatter = options.InputFormatters.OfType <JsonInputFormatter>().FirstOrDefault(); if (intputFormatter != null) { intputFormatter.SupportedMediaTypes.Add("application/vnd.cgzl.post.create+json"); intputFormatter.SupportedMediaTypes.Add("application/vnd.cgzl.post.update+json"); } var outputFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); if (outputFormatter != null) { outputFormatter.SupportedMediaTypes.Add("application/vnd.cgzl.hateoas+json"); } }) .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //资源塑性时字段小写 }) .AddFluentValidation(); //配置数据库连接, 注入数据库 services.AddDbContext <MyContext>(options => { var a = Configuration["ConnectionStrings:DefaultConnection"]; var connnectionString = Configuration.GetConnectionString("DefaultConnection"); options.UseSqlite(connnectionString); //options.UseSqlite("Data Source=BlogDemo.db"); }); //Https重定向配置 services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 5001; }); services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); //添加对象映射 services.AddAutoMapper(); //添加数据验证 services.AddTransient <IValidator <PostAddResource>, PostAddOrUpdateResourceValidator <PostAddResource> >(); services.AddTransient <IValidator <PostUpdateResource>, PostAddOrUpdateResourceValidator <PostUpdateResource> >(); //UrlHeler services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddScoped <IUrlHelper>(factory => { var actionContext = factory.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); //排序 var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <PostPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc( options => { options.ReturnHttpNotAcceptable = true; // options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); var intputFormatter = options.InputFormatters.OfType <JsonInputFormatter>().FirstOrDefault(); if (intputFormatter != null) { intputFormatter.SupportedMediaTypes.Add("application/vnd.cgzl.post.create+json"); intputFormatter.SupportedMediaTypes.Add("application/vnd.cgzl.post.update+json"); } var outputFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); if (outputFormatter != null) { outputFormatter.SupportedMediaTypes.Add("application/vnd.cgzl.hateoas+json"); } }) .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) .AddFluentValidation(); services.AddDbContext <MyContext>(options => { // var connectionString = Configuration["ConnectionStrings:DefaultConnection"]; var connectionString = Configuration.GetConnectionString("DefaultConnection"); options.UseSqlite(connectionString); }); services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 5001; }); services .AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = "https://localhost:5001"; options.ApiName = "restapi"; }); services.AddTransient <IValidator <PostAddResource>, PostAddOrUpdateResourceValidator <PostAddResource> >(); services.AddTransient <IValidator <PostUpdateResource>, PostAddOrUpdateResourceValidator <PostUpdateResource> >(); services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddScoped <IUrlHelper>(factory => { var actionContext = factory.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); services.AddAutoMapper(); services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <PostPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); services.AddTransient <ITypeHelperService, TypeHelperService>(); services.Configure <MvcOptions>(options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }); }
/// <summary> /// 服务注册 /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("any", builder => { builder.AllowAnyOrigin(); }); }); services.AddMvc(options => { options.ReturnHttpNotAcceptable = true; //支持XML 媒体格式数据 options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); }).AddJsonOptions(options => { //序列化首字母小写 options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }).AddXmlSerializerFormatters() .AddFluentValidation(); //添加Fluent验证 services.AddDbContext <ZfsDbContext>(options => { var connectionString = Configuration.GetConnectionString("DefaultConnection"); options.UseSqlite(connectionString); }); //services.AddHttpsRedirection(options => //{ // options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; // options.HttpsPort = 5001; //}); services.AddHsts(options => { options.Preload = true; options.IncludeSubDomains = true; options.MaxAge = TimeSpan.FromDays(60); }); //添加实体映射 services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //添加业务接口 services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <IMenuRepository, MenuRepository>(); services.AddScoped <ILoginLogRepository, LoginlogRepository>(); services.AddScoped <IGroupRepository, GroupRepository>(); services.AddScoped <IGroupFuncRepository, GroupFuncRepository>(); services.AddScoped <IGroupUserRepository, GroupUserRepository>(); services.AddScoped <IDictionaryTypeRepository, DictionaryTypeRepository>(); services.AddScoped <IDictionaryRepository, DictionaryRepository>(); services.AddScoped <IAuthorithitemRepository, AuthorithitemRepository>(); services.AddScoped <IUnitDbWork, UnitDbWork>(); //添加验证器 services.AddTransient <IValidator <UserViewModel>, UserViewModelValidator>(); services.AddTransient <IValidator <UserAddViewModel>, UserAddOrUpdateResourceValidator <UserAddViewModel> >(); services.AddTransient <IValidator <UserUpdateViewModel>, UserAddOrUpdateResourceValidator <UserAddOrUpdateViewModel> >(); services.AddTransient <IValidator <DictionariesViewModel>, DictionariesValidator>(); //MapContainer var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <UserPropertyMapping>(); propertyMappingContainer.Register <DictPropertyMapping>(); propertyMappingContainer.Register <GroupPropertyMappting>(); propertyMappingContainer.Register <MenuPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); services.AddTransient <ITypeHelperService, TypeHelperService>(); services.AddSwaggerGen(options => { options.IncludeXmlComments("../docs/zfsApi.xml"); options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "ZFS Service API", Version = "v1", Description = "Sample Service for Professional C#7", Contact = new Swashbuckle.AspNetCore.Swagger.Contact { Name = "trace gg", Url = "http://www.cnblogs.com/zh7791" }, }); }); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.ReturnHttpNotAcceptable = true; //options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); var inputFromatter = options.InputFormatters.OfType <JsonInputFormatter>().FirstOrDefault(); if (inputFromatter != null) { inputFromatter.SupportedMediaTypes.Add("application/vnd.hy.post.create+json"); inputFromatter.SupportedMediaTypes.Add("application/vnd.hy.post.update+json"); //inputFromatter.SupportedMediaTypes.Add("application/json-patch+json"); } var outputFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); if (outputFormatter != null) { outputFormatter.SupportedMediaTypes.Add("application/vnd.hy.hateoas+json"); } }) .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) .AddFluentValidation(); services.AddDbContext <MyContext>(options => { var connectionString = Configuration["ConnectionStrings:DefaultConnection"]; options.UseSqlite(connectionString); }); services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 5001; }); services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddAutoMapper(); services.AddTransient <IValidator <PostViewModel>, PostViewModelValidator>(); services.AddTransient <IValidator <PostAddViewModel>, PostAddOrUpdateViewModelValidator <PostAddViewModel> >(); services.AddTransient <IValidator <PostUpdateViewModel>, PostAddOrUpdateViewModelValidator <PostUpdateViewModel> >(); services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddScoped <IUrlHelper>(factory => { var actionContext = factory.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <PostPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); services.AddTransient <ITypeHelperService, TypeHelperService>(); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddCors(option => { option.AddPolicy("any", builder => { //允许localhost中8080端口跨域访问所有api builder.WithOrigins("http://localhost:8080") .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() .WithExposedHeaders("Pagination")//设置允许跨域访问中标头返回的数据 ; }); }); //添加配置MVC services.AddMvc(options => { options.ReturnHttpNotAcceptable = true; options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); }) //设置返回Json时名字首字母小写 .AddJsonOptions(option => { option.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) .AddFluentValidation(); //添加配置EF数据库 services.AddDbContext <MyDbContext>( options => { //将敏感的数据写入系统环境变量中,避免在Git上暴露信息 //连接字符串后要加 Character Set=utf8 ,不然中文会乱码 options.UseMySQL(Configuration["TestDatabaseConnectionStr"]); }); //身份认证和HTTPS重定向 //services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) // .AddIdentityServerAuthentication(options => // { // options.Authority = "https://localhost:5001"; // options.ApiName = "restapi"; // }); //services.AddHttpsRedirection(options => //{ // options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; // options.HttpsPort = 5001; //}); ////使用IdentitySever 保护API //services.Configure<MvcOptions>(options => //{ // var policy = new AuthorizationPolicyBuilder() // .RequireAuthenticatedUser().Build(); // options.Filters.Add(new AuthorizeFilter(policy)); //}); //工作单元 services.AddScoped <IUnitForWork, UnitForWork>(); //注册DAO组件 services.AddScoped <IArticleRepository, ArticleRepository>(); //添加AutoMapper services.AddAutoMapper(); //添加Mode-ViewModel的验证 services.AddTransient <IValidator <ArticleAddOrUpdateViewModel>, ArticleAddViewModelValidation>(); //添加属性字典映射服务(排序用) var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <SortArticlePropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); services.AddTransient <ITypehelper, TypeHelper>(); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddDbContext <MyContext>(options => { options.UseSqlite("Data Source=Blog.db"); }); services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 5001; }); services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = "https://localhost:5001"; options.ApiName = "restapi"; }); services.AddControllers(options => { options.ReturnHttpNotAcceptable = true; // options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()) }) .AddNewtonsoftJson(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }) .AddFluentValidation(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddScoped <IPostRepository, PostRepository>(); services.AddAutoMapper(typeof(MappingProfile).Assembly); services.AddTransient <IValidator <PostAddResource>, PostAddOrUpdateResourceValidator <PostAddResource> >(); services.AddTransient <IValidator <PostUpdateResource>, PostAddOrUpdateResourceValidator <PostUpdateResource> >(); services.AddTransient <ITypeHelperService, TypeHelperService>(); var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <PostPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); services.Configure <ApiBehaviorOptions>(options => { options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true; }); services.AddCors(options => { options.AddPolicy("AllowAngularOrigin", builder => builder.WithOrigins("http://localhost:4200") .WithExposedHeaders("X-Pagination") .AllowAnyHeader() .AllowAnyMethod()); }); services.Configure <MvcOptions>(options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }); }
public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "CodeTest API", Version = "v1" }); }); services.AddMvc( options => { options.ReturnHttpNotAcceptable = true; options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); }) .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) .AddFluentValidation(); services.AddDbContext <MyContext>(options => { var connectionString = Configuration.GetConnectionString("DefaultConnection"); options.UseSqlite(connectionString); }); services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 6001; }); services.AddTransient <IValidator <ScoreAddResource>, ScoreAddOrUpdateResourceValidator <ScoreAddResource> >(); services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddScoped <IUrlHelper>(factory => { var actionContext = factory.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); services.AddAutoMapper(typeof(Startup)); services.AddScoped <IScoreRepository, ScoreRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <ScorePropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); services.AddTransient <ITypeHelperService, TypeHelperService>(); services.AddCors(options => { options.AddPolicy("AllowAngularDevOrigin", builder => builder.WithOrigins(Configuration["ClientAddress"]) .WithExposedHeaders("X-Pagination") .AllowAnyHeader() .AllowAnyMethod()); }); services.AddSpaStaticFiles(configuration => { configuration.RootPath = @"dist"; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { #region 认证 ////清空默认绑定的用户信息 //JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); ////添加认证服务 //services.AddAuthentication(options => //{ // options.DefaultScheme = "Cookies"; //默认使用Cookies方案进行认证 // options.DefaultChallengeScheme = "oidc"; //默认认证失败时启用oidc方案 //}) //.AddCookie("Cookies") //添加Cookies认证方案 ////添加oidc方案 //.AddOpenIdConnect("oidc", options => //{ // options.SignInScheme = "Cookies"; //身份验证成功后使用Cookies方案来保存信息 // options.Authority = "http://140.143.7.32:5000"; //授权服务地址 // options.RequireHttpsMetadata = false; // options.ClientId = "mvc_implicit"; // options.ResponseType = "id_token token"; //默认只返回id_token 这里添加上token(Access Token) // options.SaveTokens = true; //}); #endregion services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); #region cookie services.AddAuthentication(AdminAuthorizeAttribute.AdminAuthenticationScheme) .AddCookie(AdminAuthorizeAttribute.AdminAuthenticationScheme, options => { options.LoginPath = "/Login/Index"; //登录路径 options.LogoutPath = "/Login/LogOut"; //退出路径 options.AccessDeniedPath = new PathString("/Error/Forbidden"); //拒绝访问页面 options.Cookie.Path = "/"; }); #endregion services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //https //services.AddHttpsRedirection(options => //{ // options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; // options.HttpsPort = 8801; //}); services.AddDbContext <ProjectDbContext>(options => { var connectionString = Configuration.GetConnectionString("DefaultConnection"); //options.UseSqlite("Data Source=MyDb.db"); options.UseSqlServer(connectionString); }, ServiceLifetime.Scoped); //mapper services.AddAutoMapper(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddScoped <ISysUserRepository, SysUserRepository>(); services.AddScoped <ISysRoleRepository, SysRoleRepository>(); services.AddScoped <ISysLogRepository, SysLogRepository>(); services.AddScoped <IBlogArticleRepository, BlogArticleRepository>(); //services.AddScoped(typeof(IBaseRepository<,>), typeof(BaseRepository<,>)); services.AddScoped <ISysUserService, SysUserService>(); services.AddScoped <ISysRoleService, SysRoleService>(); services.AddScoped <ISysLogService, SysLogService>(); services.AddScoped <IBlogArticleService, BlogArticleService>(); //排序 var propertyStringKeyMappingContainer = new PropertyMappingContainer <string>(); var propertyIntKeyMappingContainer = new PropertyMappingContainer <int>(); propertyStringKeyMappingContainer.Register <UserPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer <string> >(propertyStringKeyMappingContainer); services.AddSingleton <IPropertyMappingContainer <int> >(propertyIntKeyMappingContainer); services.AddTransient <ITypeHelperService, TypeHelperService>(); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { //注册Mvc services.AddMvc(options => { options.ReturnHttpNotAcceptable = true; //返回类型设置支持xml //options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); //设置自定义输入媒体类型 var inputFormatter = options.InputFormatters.OfType <JsonInputFormatter>().FirstOrDefault(); if (inputFormatter != null) { inputFormatter.SupportedMediaTypes.Add("application/vnd.sen.post.create+json"); inputFormatter.SupportedMediaTypes.Add("application/vnd.sen.post.update+json"); } //设置自定义输出媒体类型 var outputFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); if (outputFormatter != null) { outputFormatter.SupportedMediaTypes.Add("application/vnd.sen.hateoas+json"); } }) .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) .AddFluentValidation(); //注册DbContext services.AddDbContext <MyContext>(options => { options.UseSqlServer(this._configuration.GetConnectionString("DefaultConnection")); }); //DbContext保存 services.AddScoped <IUnitOfWork, UnitOfWork>(); //注册https services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 6001; }); //IdentityServer4.AccessTokenValidation services .AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = "https://localhost:5001"; options.ApiName = "restapi"; }); #region 添加仓储类(按字母顺序排序) services.AddScoped <IPostRepository, PostRepository>(); #endregion //添加映射 services.AddAutoMapper(typeof(MappingProfile)); #region 验证器注册(按字母顺序排序) services.AddTransient <IValidator <PostAddResource>, PostAddOrUpdateResouceValidator <PostAddResource> >(); services.AddTransient <IValidator <PostUpdateResource>, PostAddOrUpdateResouceValidator <PostUpdateResource> >(); #endregion //注册UrlHelper services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddScoped <IUrlHelper>(factory => { var actionContext = factory.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <PostPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); services.AddTransient <ITypeHelperService, TypeHelperService>(); //允许跨域 services.AddCors(options => { options.AddPolicy("AllowVueDevOrigin", builder => builder.WithOrigins("http://localhost:8020", "https://localhost:8020") .WithExposedHeaders("X-Pagination") .AllowAnyHeader() .AllowAnyMethod()); }); //全局设定只有认证用户才能访问资源 services.Configure <MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory("AllowVueDevOrigin")); var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }); }