public static void AddPropertyMappings(this IServiceCollection services) { var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <ProductPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); }
public static void AddApplicationInjection(this IServiceCollection services) { //消息组件 services.AddMediatR(AppDomain.CurrentDomain.GetAssemblies()); services.AddScoped <IMediatorHandler, InMemoryBus>(); //AutoMapper组件 services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); AutoMapper.Config.RegisterProfile(); //对外服务接口 services.AddScoped <IArticleService, ArticleService>(); services.AddScoped <IArticleUserService, ArticleUserService>(); //Domain services.AddScoped <IRequestHandler <ArticleAddCommand, bool>, ArticleCommandHandlers>(); services.AddScoped <IRequestHandler <ArticleUpdateCommand, bool>, ArticleCommandHandlers>(); services.AddScoped <IRequestHandler <ArticleDeleteCommand, bool>, ArticleCommandHandlers>(); services.AddScoped <IRequestHandler <ArticleUserAddCommand, bool>, ArticleUserCommandHandlers>(); services.AddScoped <INotificationHandler <DomainErrorNotification>, DomainErrorNotificationHandler>(); //Repository services.AddScoped <IArticleRepository, ArticleRepository>(); services.AddScoped <IArticleUserRepository, ArticleUserRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); //Redis var provider = services.BuildServiceProvider(); var config = provider.GetService <IConfiguration>(); var redisConStr = config.GetConnectionString("RedisConnection"); //services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(redisConStr)); //用于支援OrderBy参数的属性映射 var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <ArticlePropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); }
public static void AddMyServices(this IServiceCollection services) { Mapper.Reset(); services.AddAutoMapper(); services.TryAddTransient <IValidator <CityAddResource>, CityAddOrUpdateResourceValidator <CityAddResource> >(); services.TryAddTransient <IValidator <CityUpdateResource>, CityUpdateResourceValidator>(); services.TryAddTransient <IValidator <CountryAddResource>, CountryAddResourceValidator>(); services.TryAddTransient <IValidator <ProductAddResource>, ProductAddOrUpdateResourceValidator <ProductAddResource> >(); services.TryAddTransient <IValidator <ProductUpdateResource>, ProductAddOrUpdateResourceValidator <ProductUpdateResource> >(); var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <CountryPropertyMapping>(); propertyMappingContainer.Register <ProductPropertyMapping>(); services.TryAddSingleton <IPropertyMappingContainer>(propertyMappingContainer); services.TryAddTransient <ITypeHelperService, TypeHelperService>(); services.TryAddScoped(typeof(IRepository <>), typeof(EfRepository <>)); services.TryAddScoped(typeof(IEnhancedRepository <>), typeof(EfEnhancedRepository <>)); services.TryAddScoped <ICountryRepository, CountryRepository>(); services.TryAddScoped <ICityRepository, CityRepository>(); services.TryAddScoped <IProductRepository, ProductRepository>(); services.TryAddScoped <IUnitOfWork, UnitOfWork>(); services.TryAddTransient <IOrderValidator, OrderValidator>(); services.TryAddTransient <IDeliveryValidator, DeliveryValidator>(); }
public static void MappingInjection(IServiceCollection services) { var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register<PostPropertyMapping>(); services.AddSingleton<IPropertyMappingContainer>(propertyMappingContainer); }
public void ConfigureServices(IServiceCollection services) { services.AddMiddleware(); //标准写法 //var connection = Configuration["ConnectionStrings:DefaultConnection"]; //简化写法 var connection = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext <BlogContext>(options => { options.UseSqlite(connection); }); services.AddScoped <IArticleRepository, ArticleRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddAutoMapper(); //生成前一页下一页链接需要用到的,就是这样写 services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddScoped <IUrlHelper>(factory => { var actionContext = factory.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <ArticlePropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); services.AddTransient <IValidator <ArticleAddViewModel>, ArticleValidator <ArticleAddViewModel> >(); services.AddTransient <IValidator <ArticleUpdateViewModel>, ArticleValidator <ArticleUpdateViewModel> >(); }
public void ConfigureServices(IServiceCollection services) { services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 8081; }); services.AddDbContext <SolutionDbContext>(options => { options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("WebAPI.Infrastructure.Gateway")); }); //生产环境使用 services.AddHsts(options => { options.Preload = true; options.IncludeSubDomains = true; options.MaxAge = TimeSpan.FromDays(60); options.ExcludedHosts.Add("example.com"); options.ExcludedHosts.Add("www.example.com"); }); services.AddScoped <IOrderRepository, OrderRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddAutoMapper(typeof(MappingProfile)); services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddScoped <IUrlHelper>(x => { var actionContext = x.GetRequiredService <IActionContextAccessor>().ActionContext; var factory = x.GetRequiredService <IUrlHelperFactory>(); return(factory.GetUrlHelper(actionContext)); }); services.AddMvc(options => { options.ReturnHttpNotAcceptable = true; options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); options.InputFormatters.Add(new XmlDataContractSerializerInputFormatter(options)); }) .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) .AddFluentValidation(); // FluentValidation DI Step1; // FluentValidation DI Step2 services.AddTransient <IValidator <OrderAddResource>, OrderAddResourceValidator>(); services.AddTransient <IValidator <OrderUpdateResource>, OrderUpdateResourceValidator>(); // Property mapping DI var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <OrderPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); // Type Helper DI services.AddTransient <ITypeHelperService, TypeHelperService>(); }
public void ConfigureServices(IServiceCollection services) { //注册mvc中间件 services.AddMvc( options => { options.ReturnHttpNotAcceptable = true; //设置为true表示只能返回指定格式的内容,否则就会报406的错误 //options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());//新增输出的格式(指定返回的格式类型为xml) //注册自定义输出格式媒体类型 var outputFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); if (outputFormatter != null) { outputFormatter.SupportedMediaTypes.Add("application/vnd.cgzl.hateoas+json"); } }) .AddJsonOptions(options => { //所有的返回实体输出格式为前端规范的首字母小写的CamelCase规范 options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) ; //将自定义的MyContext注册到容器里,使用的时候在使用的类里面进行依赖注入即可 services.AddDbContext <MyContext>(options => { //var connectionString = Configuration["ConnectionStrings:DefaultConnection"];//使用此方法获取配置信息 var connectionString = Configuration.GetConnectionString("DefaultConnection"); options.UseSqlite(connectionString);//这里的连接串一定要写正确 不然使用程序包管理控制器的命令进行迁移的时候会报错 }); //注册HttpsRedirection中间件 services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 5001; }); //注册PostRepository,类似于这样的在.NET FrameWork里是在config文件里写,然后unity组件来进行读取,效果和这里类似 services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddAutoMapper(); //注册AutoMapper services.AddTransient <IValidator <PostResource>, PostResourceValidator>(); //注册 services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); //注册IActionContextAccessor //注册IUrlHelper 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>();//注册TypeHelperService服务 }
public static void AddPropertyMappings(this IServiceCollection services) { var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <CountryPropertyMapping>(); 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.AddMvc( options => { options.ReturnHttpNotAcceptable = true; //option.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); var outputFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); if (outputFormatter != null) { outputFormatter.SupportedMediaTypes.Add("application/vnd.cgzl.hateoas+json"); } }) .AddJsonOptions(option => { //将返回实体名称首字母改成小写 option.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); //重定向 services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 5001; }); services.AddDbContext <MyContext>(options => { //var connectionString = Configuration["ConnectionStrings:DefaultConnection"]; var connectionString = Configuration.GetConnectionString("DefaultConnection"); options.UseSqlite("Data Source=BlogDemo.db"); }); services.AddHsts(option => { option.Preload = true; option.IncludeSubDomains = true; option.MaxAge = TimeSpan.FromDays(60); option.ExcludedHosts.Add("example.com"); option.ExcludedHosts.Add("www.example.com"); }); services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddAutoMapper(); services.AddTransient <IValidator <PostResource>, PostResourceValidator>(); 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)); }); var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <PostPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); services.AddTransient <ITypeHelperService, TypeHelperService>(); }
public static void AddRESTfulAPIHelper(this IServiceCollection services, Action <RESTfulAPIHelperOptions> setupAction = null) { var options = new RESTfulAPIHelperOptions(); setupAction?.Invoke(options); var propertyMappingContainer = new PropertyMappingContainer(options); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); services.AddTransient <ITypeHelperService, TypeHelperService>(); }
public void ConfigureServices(IServiceCollection services) { //获取配置文件 var conn1 = _configuration.GetConnectionString("DefaultConnection"); var conn2 = _configuration["ConnectionStrings:DefaultConnection"]; services.AddDbContext <MyContext>(options => { options.UseSqlite("Data Source=BlogDemo.db"); }); services.AddMvc(options => { options.ReturnHttpNotAcceptable = true;//不支持客户端所需要的格式返回状态码 //支持返回xml格式 options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); }).AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); //.AddFluentValidation(); services.AddHsts(option => { option.Preload = true; option.IncludeSubDomains = true; option.MaxAge = TimeSpan.FromDays(60); option.ExcludedHosts.Add("example.com"); option.ExcludedHosts.Add("www.example.com"); }); //将http转为https services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 5001; }); //注册需要的接口 services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); //注册AotuMapper services.AddAutoMapper(typeof(MappingProfile));//9.0之后需要手动指定要注入的类型 //注册FluentValidator services.AddTransient <IValidator <PostAddResource>, PostResourceValidator <PostAddResource> >(); services.AddTransient <IValidator <PostUpdateResource>, PostResourceValidator <PostUpdateResource> >(); //IurlHelper services.AddSingleton <IActionContextAccessor, ActionContextAccessor>() .AddScoped <IUrlHelper>(sp => new UrlHelper(sp.GetRequiredService <IActionContextAccessor>().ActionContext)); //动态查询 var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <PostPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); services.AddTransient <ITypeHelperService, TypeHelperService>(); }
public IServiceCollection Register(IServiceCollection services) { var container = new PropertyMappingContainer(); container.Register <AccountResource, Account, int>(); container.Register <SysOperatorResource, Account, int>(); container.Register <RoleResource, Role, int>(); container.Register <MenuResource, Menu, int>(); services.AddSingleton <IPropertyMappingContainer>(container); return(services); }
public static void AddPropetyMapping(this IServiceCollection services) { var propetyMappingContainer = new PropertyMappingContainer(); propetyMappingContainer.Register <LoverPhotoResourceMapping>(); propetyMappingContainer.Register <LoverAlbumResourceMapping>(); propetyMappingContainer.Register <LoverLogResourceMapping>(); propetyMappingContainer.Register <LoverAnniversaryResourceMapping>(); propetyMappingContainer.Register <MenstruationLogResourceMapping>(); services.AddSingleton <IPropertyMappingContainer>(propetyMappingContainer); }
public static void AddPropertyMappings(this IServiceCollection services) { //注册排序的映射关系 QueryParameters.OrderBy var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <SongPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); //注册塑形的映射关系 Fields services.AddTransient <ITypeHelperService, TypeHelperService>(); }
public void ConfigureServices(IServiceCollection services) { //添加 MVC 支持 xml services.AddMvc(options => { options.ReturnHttpNotAcceptable = true; options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); }); //EFCore 使用,连接指定数据库 services.AddDbContext <MyContext>(options => { var connectionString = Configuration["ConnectionStrings:DefaultConnection"]; options.UseSqlite(connectionString); }); //Https配置 services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 5001; }); //Repository读取 UnitOfWork保存 services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); //映射 services.AddAutoMapper(typeof(StartupDevelopment).Assembly); //services.AddAutoMapper(profileAssemblyMarkerTypes: null); //验证 services.AddTransient <IValidator <PostResource>, PostResourceValidator>(); //前后页 services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddScoped <IUrlHelper>(factory => { var actionContext = factory.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); //排序服务 //Container 全局唯一单例 var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <PostPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1). AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) .AddFluentValidation(); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); services.AddDbContext <MyContext>( options => { options.UseMySQL(Configuration.GetConnectionString("MySQLConnection")); }); services.AddScoped <IRepository <Stock, StockParameters>, StockRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); //注册需要创建uri的服务 services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddScoped <IUrlHelper>(factory => { var actionContext = factory.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); //注册资源映射关系 MappingProfile services.AddAutoMapper(); //校验资源 //services.AddTransient<IValidator<SampleAddResource>, SampleAddOrUpdateResourceValidator<SampleAddResource>>(); //services.AddTransient<IValidator<SampleUpdateResource>, SampleAddOrUpdateResourceValidator<SampleUpdateResource>>(); //注册排序的映射关系 QueryParameters.OrderBy var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <StockPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); //注册塑形的映射关系 Fields services.AddTransient <ITypeHelperService, TypeHelperService>(); }
public void ConfigureServices(IServiceCollection services) { //services.AddMvc( // options => // { // options.ReturnHttpNotAcceptable = true; // // options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); // 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(); // }); services.AddMvc(); services.AddDbContext <MyContext>(options => { options.UseSqlite("DataSource=BlogDemo.db"); }); services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 5001; }); services.AddTransient <IValidator <PostResource>, PostResourceValidator>(); services.AddSingleton <Microsoft.AspNetCore.Mvc.Infrastructure.IActionContextAccessor, ActionContextAccessor>(); services.AddScoped <IUrlHelper>(factory => { var actionContext = factory.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddAutoMapper(); var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <PostPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); services.AddTransient <ITypeHelperService, TypeHelperService>(); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc( options => { options.ReturnHttpNotAcceptable = true; options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); }); 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.AddTransient <IValidator <PostResource>, PostResourceValidator>(); 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); }
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>(); }
public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;//转换为小写格式 //这里的转换json'为自定义媒体类型 不喜欢 }).AddFluentValidation(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "my.Core API", Description = "框架说明文档", Version = "v0.1.0", }); }); services.AddDbContext <MyContext>(options => { var connectionString = Configuration["ConnectionStrings:DefaultConnection"]; //var connectionString = Configuration.GetConnectionString("DefaultConnection"); options.UseLazyLoadingProxies().UseMySql(connectionString); }); services.AddHttpContextAccessor(); #region 使用jwt services.AddAuthorization(o => { o.AddPolicy("AdminRequireMent", o => { o.Requirements.Add(new AdminRequirement() { Name = "Admin" }); }); }); services.AddSingleton <IAuthorizationHandler, MustRoleAdminHandler>(); var symmetricKeyAsBase64 = Configuration["Audience:Secret"]; //数字签名 密钥 这个要和我们颁布时一样 var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64); var signingKey = new SymmetricSecurityKey(keyByteArray); //SymmetricSecurityKey使用对称算法生成的所有密钥的抽象基类。 services.AddAuthentication("Bearer") .AddJwtBearer(o => { o.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuerSigningKey = true, //验证密钥 IssuerSigningKey = signingKey, ValidateIssuer = true, //验证发行人 ValidIssuer = Configuration["Audience:Issuer"], ValidateAudience = true, //验证订阅人 ValidAudience = Configuration["Audience:audience"], RequireExpirationTime = true, //过期时间 ValidateLifetime = true //验证生命周期 }; }); #endregion services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 5001; }); services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddScoped <IUserRepository, UserRepositories>(); services.AddSingleton <IESSever, ESSever>(); services.AddAutoMapper(Assembly.Load("myapicode").GetTypes().Where(type => type.IsSubclassOf(typeof(Profile)) && !type.IsAbstract).ToArray()); services.AddTransient <IValidator <PostAddResource>, PostAddOrUpdateResourceValidator <PostAddResource> >(); services.AddTransient <IValidator <PostUpdateResource>, PostAddOrUpdateResourceValidator <PostUpdateResource> >(); //注册我们排序的容器 var propertyMappingContainer = new PropertyMappingContainer(); propertyMappingContainer.Register <PostPropertyMapping>(); services.AddSingleton <IPropertyMappingContainer>(propertyMappingContainer); services.AddTransient <ITypeHelperService, TypeHelperService>(); services.AddSingleton <IConnectionMultiplexer>(ConnectionMultiplexer.Connect("localhost")); #region jwt 学习 先通过bearer认证 再注册jwrbearer服务 //JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();//紧张net core对jwt的进行配置映射 //var symmetricKeyAsBase64 = Configuration["Audience:Secret"];//数字签名 密钥 这个要和我们颁布时一样 //var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64); //var signingKey = new SymmetricSecurityKey(keyByteArray);//SymmetricSecurityKey使用对称算法生成的所有密钥的抽象基类。 //var tokenValidationParameters = new TokenValidationParameters() //{//常用的几个单词 Issuer颁发者 Signing签名 Audience观众 // ValidateIssuerSigningKey = true,//是否开启密钥认证 // IssuerSigningKey = signingKey, // ValidateIssuer = true, // ValidIssuer = "http://localhost:5001",//发行人 // ValidateAudience = true, // ValidAudience = "http://localhost:5000",//订阅人 // ValidateLifetime = true, // ClockSkew = TimeSpan.FromSeconds(30),//时钟偏斜 // RequireExpirationTime = true //}; ////注入服务 //services.AddAuthentication("Bearer").AddJwtBearer(o => //{//注册jwtBearer服务 // o.TokenValidationParameters = tokenValidationParameters; //}); #endregion }
// 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.AddHttpsRedirection(config => { config.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; config.HttpsPort = 5001; //与launchSettings.json 配置文件保持一致 }); //启用授权 services.AddAuthorization(); //启用验证 services.AddAuthentication("Bearer") .AddIdentityServerAuthentication(options => { options.RequireHttpsMetadata = true; options.Authority = "https://localhost:5001"; options.ApiName = "socialnetwork"; }); services.AddMvc(options => { // 启用http 内容协商,客户端 accept header 支持406 options.ReturnHttpNotAcceptable = true; //net core 默认返回格式为json,这里添加xml格式 key=Accept value=application/xml //options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); //自定义Media Type var intputFormatter = options.InputFormatters.OfType <JsonInputFormatter>().FirstOrDefault(); if (intputFormatter != null) { intputFormatter.SupportedMediaTypes.Add("application/vnd.huaisan.post.create+json"); intputFormatter.SupportedMediaTypes.Add("application/vnd.huaisan.post.update+json"); } var outputFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); if (outputFormatter != null) { outputFormatter.SupportedMediaTypes.Add("application/vnd.huaisan.hateoas+json"); } }) .AddJsonOptions(options => { // 确保json返回为驼峰类型,即首字母小写 options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) .AddFluentValidation(); #region 读取json配置文件 //services.AddDbContext<MyContext>(options=> { // options.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=BlogDemo;Trusted_Connection=True;MultipleActiveResultSets=true"); //}); //方法一: //var connectionString = _configuration["ConnectionStrings:DefaultConnection"]; //方法二: string connectionString = _configuration.GetConnectionString("DefaultConnection"); services.AddDbContext <MyContext>(options => { options.UseSqlServer(connectionString); }); #endregion services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); //使用aotumapper services.AddAutoMapper(); //fluentValidation services.AddTransient <IValidator <PostAddResource>, PostAddOrUpdateResourceValidator <PostAddResource> >(); services.AddTransient <IValidator <PostUpdateResource>, PostAddOrUpdateResourceValidator <PostUpdateResource> >(); //添加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); //添加自定义方法,controller ctor方法注入时使用 services.AddTransient <ITypeService, TypeService>(); }
public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Blog API", Version = "v1" }); }); 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 = 6001; }); services .AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { //options.Authority = "https://*****:*****@"dist"; }); }
// 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 // 服务注册,可被下面的Configure调用 public void ConfigureServices(IServiceCollection services) { // 注册MVC服务 services.AddMvc( options => { // media type在header里传进不支持的格式时报406 options.ReturnHttpNotAcceptable = true; // 输出xml的支持 // options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); var inputFormatter = options.InputFormatters.OfType <JsonInputFormatter>().FirstOrDefault(); if (inputFormatter != null) { inputFormatter.SupportedMediaTypes.Add("application/vnd.shine.post.create+json"); inputFormatter.SupportedMediaTypes.Add("application/vnd.shine.post.update+json"); } // 自定义媒体类型 var outputFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); if (outputFormatter != null) { outputFormatter.SupportedMediaTypes.Add("application/vnd.shine.hateoas+json"); } }) // 塑性之后Json字段首字母变成了大写,此方法改回小写 .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) .AddFluentValidation(); // 注册Https重定向服务 services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 5001; }); // 身份认证 services .AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = "https://localhost:5001"; options.ApiName = "restapi"; }); // 注册HSTS(Http Strict Transport Security Protocol),微软建议使用 //services.AddHsts(options => //{ // options.Preload = true; // options.IncludeSubDomains = true; // options.MaxAge = TimeSpan.FromDays(60); // options.ExcludedHosts.Add("example.com"); // options.ExcludedHosts.Add("www.example.com"); //}); services.AddDbContext <MyContext>(options => { // var connectionString = Configuration["ConnectionStrings:DefaultConnection"]; var connectionString = Configuration.GetConnectionString("DefaultConnection"); // 数据库连接字符串 options.UseSqlite(connectionString); }); // 注册仓储服务 services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); // 注册映射 services.AddAutoMapper(); services.AddTransient <IValidator <PostAddResource>, PostAddOrUpdateResourceValidator <PostAddResource> >(); services.AddTransient <IValidator <PostUpdateResource>, PostAddOrUpdateResourceValidator <PostUpdateResource> >(); // 注册uri //官方文档 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>(); // 全局认证,针对所有的Controller services.Configure <MvcOptions>(options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => {//406输入格式支持问题,默认application/json 现在添加application/xml的支持 options.ReturnHttpNotAcceptable = true; //options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); //创建特定的媒体类型(输出) var outputFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); if (outputFormatter != null) { outputFormatter.SupportedMediaTypes.Add("application/vnd.cgzl.hateoas+json"); } }) //添加字段限制 .AddFluentValidation() //这只是小写 .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); //ef 直接建立到本地的了 services.AddDbContext <MyContext>( options => { //var connectionstrings = _configuration["ConnectionStrings:DefaultConnection"]; // var connectionstring = _configuration.GetConnectionString("DefaultConnection"); options.UseSqlite("Data Source=BlogDemo.db"); }); //https services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 6001; }); #region identityServer4 services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = "https://localhost:5001"; options.ApiName = "restapi"; }); #endregion //这些官网都有的,可以去看,连接在笔记中 //映射 services.AddAutoMapper(ctf => { ctf.AddProfile <MypingProfile>(); }, AppDomain.CurrentDomain.GetAssemblies()); //验证resource 包含约束 // services.AddTransient<IValidator<PostAddResource>, PostAddResourceValidator>(); services.AddTransient <IValidator <PostAddResource>, PostAddOrUpdateResourceValidator <PostAddResource> >(); services.AddTransient <IValidator <PostUpdateResource>, PostAddOrUpdateResourceValidator <PostUpdateResource> >(); //图片上传 services.AddTransient <IValidator <PostImageResource>, PostImageResourceValidator>(); #region 接口注册 自写 services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddScoped <IPostImageRepository, PostImageRepository>(); #endregion 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("AllowAngularDevOrign" , builder => builder.WithOrigins("http://localhost:4200")//起源 .WithHeaders("X-pagination") .AllowAnyHeader() .AllowAnyMethod()); }); //https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2 //全局加入身份验证 services.Configure <MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAngularDevOrign")); var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }); }
// 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 = false; //options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); var inputFormatter = options.InputFormatters.OfType <JsonInputFormatter>().FirstOrDefault(); if (inputFormatter != null) { inputFormatter.SupportedMediaTypes.Add("application/vnd.awind.create+json"); inputFormatter.SupportedMediaTypes.Add("application/vnd.awind.update+json"); } var outputFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); if (outputFormatter != null) { outputFormatter.SupportedMediaTypes.Add("application/vnd.awind.hateoas+json"); } }).AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }).AddFluentValidation(); services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 6001; }); services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = "https://localhost:5001"; options.ApiName = "restapi"; }); services.AddDbContext <MyContext>(options => { options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")); }); services.AddScoped <IPostImageRepository, PostImageRepository>(); services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddAutoMapper(); services.AddTransient <IValidator <PostAddResource>, PostAddOrUpdateResourceValidator <PostAddResource> >(); services.AddTransient <IValidator <PostUpdateResource>, PostAddOrUpdateResourceValidator <PostUpdateResource> >(); services.AddTransient <IValidator <PostImageResource>, PostImageResourceValidator>(); 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("AllowAngularDevOrigin", builder => builder.WithOrigins("http://localhost:4200") .WithExposedHeaders("X-Pagination") .AllowAnyHeader() .AllowAnyMethod() ); }); services.Configure <MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAngularDevOrigin")); var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }); }
public PropertyMappingContainerShould() { _propertyMappingContainer = new PropertyMappingContainer(); }
// 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; //option.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); var intputFormatter = options.InputFormatters.OfType <JsonInputFormatter>().FirstOrDefault(); if (intputFormatter != null) { intputFormatter.SupportedMediaTypes.Add("application/json-patch+json"); } var outputFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); if (outputFormatter != null) { outputFormatter.SupportedMediaTypes.Add("application/hateoas+json"); } }) .AddJsonOptions(option => { //将返回实体名称首字母改成小写 option.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) .AddFluentValidation(); //重定向 services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 6001; }); services.AddDbContext <MyContext>(options => { //var connectionString = Configuration["ConnectionStrings:DefaultConnection"]; var connectionString = Configuration.GetConnectionString("DefaultConnection"); options.UseSqlite("Data Source=BlogDemo.db"); }); services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.ApiName = "restapi"; options.Authority = "https://localhost:5001"; //令牌发行者的基本地址 }); services.AddHsts(option => { option.Preload = true; option.IncludeSubDomains = true; option.MaxAge = TimeSpan.FromDays(60); option.ExcludedHosts.Add("example.com"); option.ExcludedHosts.Add("www.example.com"); }); services.AddScoped <IPostRepository, PostRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddAutoMapper(); services.AddTransient <IValidator <PostResource>, PostResourceValidator>(); 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)); }); 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)); }); }
// 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 }
// 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)); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddMvc(options => { options.ReturnHttpNotAcceptable = true; options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); }).AddXmlSerializerFormatters(); //services.AddSwaggerGen(options => options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "SwaggerApiTest", Version = "v1" })); services.AddCors(options => { options.AddPolicy("any", builder => { builder.AllowAnyOrigin(); }); }); services.AddMvc(options => { options.ReturnHttpNotAcceptable = true; //支持XML 媒体格式数据 options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); }).AddNewtonsoftJson(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 Microsoft.OpenApi.Models.OpenApiInfo { Title = "ZFS Service API", Version = "v1", Description = "Sample Service for Professional C#7", Contact = new Microsoft.OpenApi.Models.OpenApiContact { Name = "trace gg", //Url = new Uri("http://www.cnblogs.com/zh7791"), }, }); }); //services.AddMvc(options => { options.EnableEndpointRouting = false; }); }