protected AdvancedAcceptanceTest() { FilteredControllerTypes.Add(typeof(OrdersController)); FilteredControllerTypes.Add(typeof(Orders2Controller)); FilteredControllerTypes.Add(typeof(Orders3Controller)); FilteredControllerTypes.Add(typeof(PeopleController)); FilteredControllerTypes.Add(typeof(People2Controller)); Configuration.AddApiVersioning( options => { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = true; options.ApiVersionReader = ApiVersionReader.Combine( new QueryStringApiVersionReader(), new HeaderApiVersionReader("api-version", "x-ms-version")); }); var modelBuilder = new VersionedODataModelBuilder(Configuration) { ModelConfigurations = { new PersonModelConfiguration(), new OrderModelConfiguration(supportedApiVersion: new ApiVersion(2, 0)) } }; var models = modelBuilder.GetEdmModels(); Configuration.MapVersionedODataRoutes("odata", "api", models, OnConfigureContainer); Configuration.Routes.MapHttpRoute("orders", "api/{controller}/{key}", new { key = Optional }); Configuration.EnsureInitialized(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddApiVersioning(cfg => { cfg.DefaultApiVersion = new ApiVersion(1, 0); cfg.AssumeDefaultVersionWhenUnspecified = true; cfg.ReportApiVersions = true; cfg.ApiVersionReader = ApiVersionReader.Combine( new HeaderApiVersionReader("X-Version"), new QueryStringApiVersionReader("ver") ); cfg.Conventions .Controller <PlayerController>() .HasApiVersion(new ApiVersion(1, 0)); cfg.Conventions .Controller <PlayerController>() .HasApiVersion(new ApiVersion(1, 1)); }); services.AddHsts(options => { options.IncludeSubDomains = true; options.MaxAge = TimeSpan.FromDays(365); }); }
public void ConfigureServices(IServiceCollection services) { services.AddDbContext <CampContext>(); services.AddScoped <ICampRepository, CampRepository>(); services.AddAutoMapper(typeof(Startup)); services.AddApiVersioning(opt => { opt.AssumeDefaultVersionWhenUnspecified = true; opt.DefaultApiVersion = new ApiVersion(1, 1); opt.ReportApiVersions = true; opt.ApiVersionReader = ApiVersionReader.Combine( new HeaderApiVersionReader("X-Version"), new QueryStringApiVersionReader("v", "ver", "version")); opt.Conventions.Controller <TalksController>() .HasApiVersion(new ApiVersion(1, 0)) .HasApiVersion(new ApiVersion(1, 1)) .Action(c => c.DeleteTalk(default(string), default(int))) .MapToApiVersion(new ApiVersion(1, 1)); }); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
public static void AddSwagger(this IServiceCollection services) { services.AddApiVersioning( options => { options.ReportApiVersions = true; options.ApiVersionReader = ApiVersionReader.Combine( new HeaderApiVersionReader("api-version"), new QueryStringApiVersionReader("v")); }); services.AddVersionedApiExplorer( options => { options.GroupNameFormat = "'v'VVV"; options.SubstituteApiVersionInUrl = true; }); services.AddSwaggerGen( options => { options.OperationFilter <SwaggerDefaultValues>(); options.IncludeXmlComments(XmlCommentsFilePath); }); }
public void add_api_versioning_should_configure_mvc_with_custom_options() { // arrange var services = new ServiceCollection(); services.AddMvcCore(); // act services.AddApiVersioning( options => { options.ReportApiVersions = true; options.ApiVersionReader = ApiVersionReader.Combine(new QueryStringApiVersionReader(), new HeaderApiVersionReader("api-version")); options.ApiVersionSelector = new ConstantApiVersionSelector(new ApiVersion(DateTime.Today)); }); // assert services.Single(sd => sd.ServiceType == typeof(IApiVersionReader)).ImplementationFactory.Should().NotBeNull(); services.Single(sd => sd.ServiceType == typeof(IApiVersionSelector)).ImplementationFactory.Should().NotBeNull(); services.Single(sd => sd.ServiceType == typeof(IErrorResponseProvider)).ImplementationFactory.Should().NotBeNull(); services.Single(sd => sd.ServiceType == typeof(IActionSelector)).ImplementationType.Should().Be(typeof(ApiVersionActionSelector)); services.Single(sd => sd.ServiceType == typeof(IApiVersionRoutePolicy)).ImplementationType.Should().Be(typeof(DefaultApiVersionRoutePolicy)); services.Single(sd => sd.ServiceType == typeof(IApiControllerFilter)).ImplementationType.Should().Be(typeof(DefaultApiControllerFilter)); services.Single(sd => sd.ServiceType == typeof(ReportApiVersionsAttribute)).ImplementationType.Should().Be(typeof(ReportApiVersionsAttribute)); services.Single(sd => sd.ServiceType == typeof(IReportApiVersions)).ImplementationFactory.Should().NotBeNull(); services.Any(sd => sd.ServiceType == typeof(IPostConfigureOptions <MvcOptions>) && sd.ImplementationType == typeof(ApiVersioningMvcOptionsSetup)).Should().BeTrue(); services.Any(sd => sd.ServiceType == typeof(IPostConfigureOptions <RouteOptions>) && sd.ImplementationType == typeof(ApiVersioningRouteOptionsSetup)).Should().BeTrue(); services.Any(sd => sd.ServiceType == typeof(IApplicationModelProvider) && sd.ImplementationType == typeof(ApiVersioningApplicationModelProvider)).Should().BeTrue(); services.Any(sd => sd.ServiceType == typeof(IActionDescriptorProvider) && sd.ImplementationType == typeof(ApiVersionCollator)).Should().BeTrue(); services.Any(sd => sd.ServiceType == typeof(IApiControllerSpecification) && sd.ImplementationType == typeof(ApiBehaviorSpecification)).Should().BeTrue(); services.Any(sd => sd.ServiceType == typeof(MatcherPolicy) && sd.ImplementationType == typeof(ApiVersionMatcherPolicy)).Should().BeTrue(); }
public void add_api_versioning_should_configure_mvc_with_custom_options() { // arrange var services = new ServiceCollection(); var mvcOptions = new MvcOptions(); var routeOptions = new RouteOptions(); services.AddMvc(); services.AddApiVersioning( o => { o.ReportApiVersions = true; o.ApiVersionReader = ApiVersionReader.Combine(new QueryStringApiVersionReader(), new HeaderApiVersionReader("api-version")); o.ApiVersionSelector = new ConstantApiVersionSelector(new ApiVersion(DateTime.Today)); }); var serviceProvider = services.BuildServiceProvider(); var mvcConfiguration = serviceProvider.GetRequiredService <IConfigureOptions <MvcOptions> >(); var routeConfiguration = serviceProvider.GetRequiredService <IConfigureOptions <RouteOptions> >(); // act mvcConfiguration.Configure(mvcOptions); routeConfiguration.Configure(routeOptions); // assert services.Single(sd => sd.ServiceType == typeof(IApiVersionReader)).ImplementationInstance.Should().NotBeNull(); services.Single(sd => sd.ServiceType == typeof(IApiVersionSelector)).ImplementationInstance.Should().BeOfType <ConstantApiVersionSelector>(); services.Single(sd => sd.ServiceType == typeof(IActionSelector)).ImplementationType.Should().Be(typeof(ApiVersionActionSelector)); services.Single(sd => sd.ServiceType == typeof(ReportApiVersionsAttribute)).ImplementationType.Should().Be(typeof(ReportApiVersionsAttribute)); mvcOptions.Filters.OfType <TypeFilterAttribute>().Single().ImplementationType.Should().Be(typeof(ReportApiVersionsAttribute)); mvcOptions.Conventions.Single().Should().BeOfType <ApiVersionConvention>(); routeOptions.ConstraintMap["apiVersion"].Should().Be(typeof(ApiVersionRouteConstraint)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <SiteContext>() .AddEntityFrameworkInMemoryDatabase(); services.AddScoped <ISiteRepository, SiteRepository>(); services.AddAutoMapper(typeof(Startup)); services.AddHttpCacheHeaders(opt => opt.MaxAge = 600); services.AddResponseCaching(); services.AddApiVersioning(cfg => { cfg.ReportApiVersions = true; cfg.DefaultApiVersion = new ApiVersion(2, 0); cfg.AssumeDefaultVersionWhenUnspecified = true; cfg.ApiVersionReader = ApiVersionReader.Combine( new AcceptHeaderApiVersionReader(), new QueryStringApiVersionReader("v"), new HeaderApiVersionReader("X-Version")); }); services.AddMvc(cfg => { cfg.RespectBrowserAcceptHeader = true; }) .AddXmlSerializerFormatters() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
public static void Register(HttpConfiguration config) { // Web API configuration, versioning and services config.AddApiVersioning(cfg => { cfg.DefaultApiVersion = new ApiVersion(1, 0); cfg.AssumeDefaultVersionWhenUnspecified = true; cfg.ReportApiVersions = true; cfg.ApiVersionReader = ApiVersionReader.Combine( new HeaderApiVersionReader("X-Version"), new QueryStringApiVersionReader("ver")); //Versioning Conventions example cfg.Conventions.Controller <ProductController>() .HasApiVersion(1, 0) .HasApiVersion(1, 1) .Action(m => m.Delete(default(Guid))); }); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors); }
public static IServiceCollection AddWeb( this IServiceCollection services, IConfiguration configuration) { //attach the the model validator and define the api grouping convention //setup fluent validation for the running assembly services.AddMvc( options => { options.Filters.Add <ValidateModelFilter>(); options.Conventions.Add(new GroupByApiRootConvention()); }) .AddJsonOptions(opt => { opt.JsonSerializerOptions.IgnoreNullValues = true; }) .AddFluentValidation(cfg => { cfg.RegisterValidatorsFromAssemblyContaining <Startup>(); }) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddScoped <ICurrentUser, CurrentUser>(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddScoped <IUrlHelper, UrlHelper>( implementationFactory => { var actionContext = implementationFactory.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); services.AddHttpCacheHeaders( expirationModelOptionsAction => { expirationModelOptionsAction.MaxAge = 120; }, validationModelOptionsAction => { validationModelOptionsAction.MustRevalidate = true; }); services.AddResponseCaching(); services.AddMemoryCache(); //Can be rate limited by Client Id as well //ClientRateLimitOptions services.Configure <IpRateLimitOptions>(configuration.GetSection("IpRateLimiting")); services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>(); services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(); services.AddSingleton <IRateLimitConfiguration, RateLimitConfiguration>(); services.AddApiVersioning( config => { // Specify the default API Version config.DefaultApiVersion = new ApiVersion(1, 0); // If the client hasn't specified the API version in the request, use the default API version number config.AssumeDefaultVersionWhenUnspecified = true; // Advertise the API versions supported for the particular endpoint config.ReportApiVersions = true; // Supporting multiple versioning scheme config.ApiVersionReader = ApiVersionReader.Combine( new HeaderApiVersionReader("X-version"), new QueryStringApiVersionReader("api-version")); }); return(services); }
public static IServiceCollection AddCustomApiVersioning(this IServiceCollection services, IConfiguration configuration) => services.AddApiVersioning(setup => { setup.ReportApiVersions = true; setup.AssumeDefaultVersionWhenUnspecified = true; setup.DefaultApiVersion = new ApiVersion(configuration.GetValue <int>("ApiVersion:Major"), configuration.GetValue <int>("ApiVersion:Minor")); setup.ApiVersionReader = ApiVersionReader.Combine(new HeaderApiVersionReader("x-version"), new QueryStringApiVersionReader("api-version")); });
protected override void OnAddApiVersioning(ApiVersioningOptions options) { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = true; options.ApiVersionReader = ApiVersionReader.Combine( new QueryStringApiVersionReader(), new HeaderApiVersionReader("api-version", "x-ms-version")); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(config => { config.Filters.Add <JsonExceptionFilter>(); config.ReturnHttpNotAcceptable = true; config.OutputFormatters.Add(new XmlSerializerOutputFormatter()); config.CacheProfiles.Add("Default", new CacheProfile() { Duration = 60 }); config.CacheProfiles.Add("Never", new CacheProfile() { Location = ResponseCacheLocation.None, NoStore = true }); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddAutoMapper(); services.AddDbContext <LibraryDbContext>(config => config.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddScoped <IRepositoryWrapper, RepositoryWrapper>(); services.AddScoped <CheckAuthorExistFilterAttribute>(); services.AddGraphQLSchemaAndTypes(); services.AddSingleton <IHashFactory, HashFactory>(); services.AddResponseCaching(); services.AddMemoryCache(); services.AddDistributedRedisCache(options => { options.Configuration = Configuration["Caching:Host"]; options.InstanceName = Configuration["Caching:Instance"]; }); services.AddApiVersioning(options => { options.ReportApiVersions = true; options.DefaultApiVersion = new ApiVersion(1, 0); options.AssumeDefaultVersionWhenUnspecified = true; // options.ApiVersionReader = new QueryStringApiVersionReader("ver"); // options.ApiVersionReader = new HeaderApiVersionReader("api-version"); //options.ApiVersionReader = new MediaTypeApiVersionReader(); options.ApiVersionReader = ApiVersionReader.Combine( new MediaTypeApiVersionReader(), new QueryStringApiVersionReader("api-version")); options.Conventions.Controller <Controllers.V1.ProjectController>() .HasApiVersion(new ApiVersion(1, 0)) .HasDeprecatedApiVersion(new ApiVersion(1, 0)); options.Conventions.Controller <Controllers.V2.ProjectController>() .HasApiVersion(new ApiVersion(2, 0)); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service // note: the specified format code will format the version as "'v'major[.minor][-status]" services.AddMvcCore().AddVersionedApiExplorer( options => { options.GroupNameFormat = "'v'VVV"; // note: this option is only necessary when versioning by url segment. the SubstitutionFormat // can also be used to control the format of the API version in route templates options.SubstituteApiVersionInUrl = true; } ); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddApiVersioning( options => { options.DefaultApiVersion = new ApiVersion(1, 0); var versionString = "api-version"; options.ApiVersionReader = ApiVersionReader.Combine( new QueryStringApiVersionReader(versionString), new HeaderApiVersionReader(versionString), new MediaTypeApiVersionReader(versionString) ); options.ReportApiVersions = true; } ); services.AddSwaggerGen( options => { // resolve the IApiVersionDescriptionProvider service // note: that we have to build a temporary service provider here because one has not been created yet using (var serviceProvider = services.BuildServiceProvider()) { var provider = serviceProvider.GetRequiredService <IApiVersionDescriptionProvider>(); // add a swagger document for each discovered API version // note: you might choose to skip or document deprecated API versions differently foreach (var description in provider.ApiVersionDescriptions) { options.SwaggerDoc(description.GroupName, CreateInfoForApiVersion(description)); } } // add a custom operation filter which sets default values options.OperationFilter <SwaggerDefaultValues>(); // integrate xml comments options.IncludeXmlComments(XmlCommentsFilePath); } ); }
// 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.AddControllers(); services.AddApiVersioning(v => { v.AssumeDefaultVersionWhenUnspecified = true; v.DefaultApiVersion = new ApiVersion(1, 0); v.ReportApiVersions = true; v.ApiVersionReader = ApiVersionReader.Combine( new HeaderApiVersionReader("X-Version"), new QueryStringApiVersionReader("ver", "version"), new UrlSegmentApiVersionReader()); } ); services.AddSwaggerGen(setupAction => { var xmlFile = "LatihanOpenAPI.xml"; var xmlFullPath = Path.Combine(AppContext.BaseDirectory, xmlFile); setupAction.IncludeXmlComments(xmlFullPath); setupAction.SwaggerDoc("LatihanOpenAPICategory", new OpenApiInfo() { Title = "Latihan Open API-Category", Version = "1", Description = "Latihan membuat Web API dengan menggunakan.Net Core - Category", Contact = new OpenApiContact() { Email = "*****@*****.**", Name = "Junindar", Url = new Uri("http://junindar.blogspot.com") } }); setupAction.SwaggerDoc("LatihanOpenAPIBook", new OpenApiInfo() { Title = "Latihan Open API-Book", Version = "1", Description = "Latihan membuat Web API dengan menggunakan.Net Core - Book", Contact = new OpenApiContact() { Email = "*****@*****.**", Name = "Junindar", Url = new Uri("http://junindar.blogspot.com") } }); }); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddDbContext <PustakaDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("pustakaConnection"))); services.AddTransient <IBookRepository, BookRepository>(); services.AddTransient <ICategoryRepository, CategoryRepository>(); }
private void GetApiVersioningOptions(ApiVersioningOptions apiVersioningOptions) { apiVersioningOptions.AssumeDefaultVersionWhenUnspecified = true; apiVersioningOptions.ReportApiVersions = true; apiVersioningOptions.DefaultApiVersion = new ApiVersion(1, 0); apiVersioningOptions.ApiVersionReader = ApiVersionReader.Combine(new QueryStringApiVersionReader(), new HeaderApiVersionReader("X-Version"), new UrlSegmentApiVersionReader()); }
/// <summary> /// Configures services for the application. /// </summary> /// <param name="services">The collection of services to configure the application with.</param> public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddApiVersioning(options => { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = new ApiVersion(1, 0); // Allow version to be specified in header options.ApiVersionReader = ApiVersionReader.Combine( new QueryStringApiVersionReader(), new HeaderApiVersionReader("api-version", "x-ms-version")); }); services.AddOData().EnableApiVersioning(); // Place after AddOData to avoid issues with formatters not being available services.AddMvcCore(options => { var formatters = options.OutputFormatters.OfType <ODataOutputFormatter>() .Where(_ => _.SupportedMediaTypes.Count == 0); foreach (var formatter in formatters) { formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/odata")); } }); services.AddODataApiExplorer( options => { // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service // note: the specified format code will format the version as "'v'major[.minor][-status]" options.GroupNameFormat = "'v'VVV"; // note: this option is only necessary when versioning by url segment. the SubstitutionFormat // can also be used to control the format of the API version in route templates options.SubstituteApiVersionInUrl = true; }); services.AddSwaggerGen( options => { // add a custom operation filter which sets default values options.OperationFilter <SwaggerDefaultValues>(); // integrate xml comments options.IncludeXmlComments(XmlCommentsFilePath()); }); string XmlCommentsFilePath() { var basePath = PlatformServices.Default.Application.ApplicationBasePath; var fileName = typeof(Startup).GetTypeInfo().Assembly.GetName().Name + ".xml"; return(Path.Combine(basePath, fileName)); } }
public void ConfigureServices(IServiceCollection services) { // Add the DbContext //services.AddDbContext<IMISContext>(options => options.UseSqlServer(Configuration.GetConnectionString("IMISDatabase"))); services.AddSingleton <IImisModules, ImisModules>(); // Add the authentication scheme with the custom validator services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidIssuer = Configuration["JwtIssuer"], ValidAudience = Configuration["JwtAudience"] }; options.SecurityTokenValidators.Clear(); //below line adds the custom validator class options.SecurityTokenValidators.Add(new IMISJwtSecurityTokenHandler(services.BuildServiceProvider().GetService <IImisModules>())); }); services.AddAuthorization(); //(options => //{ // options.AddPolicy("MedicalOfficer", policy => policy.Requirements.Add(new HasAuthorityRequirement("MedicalOfficer", Configuration["JwtIssuer"]))); // options.AddPolicy("EnrollmentOfficer", policy => policy.Requirements.Add(new HasAuthorityRequirement("EnrollmentOfficer", Configuration["JwtIssuer"]))); //}); // register the scope authorization handler services.AddSingleton <IAuthorizationPolicyProvider, AuthorizationPolicyProvider>(); services.AddSingleton <IAuthorizationHandler, HasAuthorityHandler>(); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddApiVersioning(o => { o.ReportApiVersions = true; o.AssumeDefaultVersionWhenUnspecified = true; o.DefaultApiVersion = new ApiVersion(1, 0); o.ApiVersionReader = ApiVersionReader.Combine(new QueryStringApiVersionReader(), new HeaderApiVersionReader("api-version")); }); services.AddSwaggerGen(SwaggerHelper.ConfigureSwaggerGen); services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowCredentials().AllowAnyHeader()); }); }
public override IServiceProvider ConfigureServices(IServiceCollection services) { //JWT services.AddJwtToken(Configuration); services.AddWebApiAuth(Configuration, Environment); services.AddMvc(opts => { opts.Filters.Add(typeof(VinoActionFilter)); opts.Filters.Add(typeof(WebApiResultFilter)); opts.Filters.Add(typeof(ApiExceptionFilter)); }) .AddJsonOptions(json => { // 忽略循环引用 json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //不使用驼峰样式的key json.SerializerSettings.ContractResolver = new DefaultContractResolver(); //设置时间格式 json.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; json.SerializerSettings.Converters.Add(new LongToStringConverter()); json.SerializerSettings.Converters.Add(new EnumDisplayConverter()); }); //版本控制 services.AddApiVersioning(option => { option.ReportApiVersions = true; option.AssumeDefaultVersionWhenUnspecified = true; option.DefaultApiVersion = new ApiVersion(1, 0); option.ApiVersionReader = ApiVersionReader.Combine(new HeaderApiVersionReader("api-version"), new QueryStringApiVersionReader("api-version")); }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "Vino.Core.CMS 接口文档", Description = "RESTful API for Vino.Core.CMS", TermsOfService = "None", Contact = new Contact { Name = "Kulend", Email = "*****@*****.**", Url = "" } }); //Set the comments path for the swagger json and ui. var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "Vino.Core.CMS.WebApi.xml"); c.IncludeXmlComments(xmlPath); // c.OperationFilter<HttpHeaderOperation>(); // 添加httpHeader参数 }); return(base.ConfigureServices(services)); }
public static void Register(HttpConfiguration config) { config.Services.Replace(typeof(IExceptionHandler), new LogExceptionHandler()); //config.Services.Insert(typeof(ModelBinderProvider), 0, new DateTimeModelBinderProvider()); config.BindParameter(typeof(DateTime), new UtcDateTimeModelBinder()); config.BindParameter(typeof(DateTime?), new UtcDateTimeModelBinder()); //// Add model validation, globally //config.Filters.Add(new ValidationActionFilterAttribute()); // Web API configuration and services // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); config.AddApiVersioning(cfg => { cfg.DefaultApiVersion = new ApiVersion(1, 1); cfg.AssumeDefaultVersionWhenUnspecified = true; cfg.ReportApiVersions = true; //cfg.ApiVersionReader = new UrlSegmentApiVersionReader(); cfg.ApiVersionReader = ApiVersionReader.Combine( new HeaderApiVersionReader("X-Version"), new QueryStringApiVersionReader("ver")); //cfg.Conventions.Controller<TicketController>() // .HasApiVersion(1, 0) // .HasApiVersion(1, 1) // .Action(m => m.Get(default, default, default)) // .MapToApiVersion(2, 0); }); // Use camel case for JSON data. config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Add model validation, globally config.Filters.Add(new ValidationActionFilterAttribute()); //config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None; var constraintResolver = new DefaultInlineConstraintResolver { ConstraintMap = { ["apiVersion"] = typeof(ApiVersionRouteConstraint) } }; // Web API routes config.MapHttpAttributeRoutes(constraintResolver); DefineRoutes(config); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddApiVersioning(config => { config.DefaultApiVersion = new ApiVersion(1, 0); config.AssumeDefaultVersionWhenUnspecified = true; config.ReportApiVersions = true; config.ApiVersionReader = ApiVersionReader.Combine(new UrlSegmentApiVersionReader()); }); }
/// <summary> /// Adds ShoppingIt api versioning middleware. /// </summary> /// <param name="services">The service collection.</param> /// <returns>Returns the service collection with ShoppingIt api versioning.</returns> public static IServiceCollection AddShoppingItApiVersioning(this IServiceCollection services) { services.AddApiVersioning(config => { config.DefaultApiVersion = new ApiVersion(1, 0); config.AssumeDefaultVersionWhenUnspecified = true; config.ReportApiVersions = true; config.ApiVersionReader = ApiVersionReader.Combine(new HeaderApiVersionReader("X-version"), new QueryStringApiVersionReader("api-version")); }); return(services); }
public static IServiceCollection AddCustomApiVersion(this IServiceCollection services) { return(services.AddApiVersioning(options => { options.ApiVersionReader = ApiVersionReader.Combine( new QueryStringApiVersionReader("api-version"), new HeaderApiVersionReader("api-version")); options.DefaultApiVersion = new ApiVersion(1, 0); options.AssumeDefaultVersionWhenUnspecified = true; options.ReportApiVersions = true; })); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddDbContext <RestaurantGuideContext>(opt => opt.UseMySql(Configuration.GetConnectionString("DefaultConnection"))); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // configure strongly typed settings objects var appSettingsSection = Configuration.GetSection("AppSettings"); services.Configure <AppSettings>(appSettingsSection); // configure jwt authentication var appSettings = appSettingsSection.Get <AppSettings>(); var key = Encoding.ASCII.GetBytes(appSettings.Secret); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; }); // configure DI for application services services.AddScoped <IUserService, UserService>(); // Register the Swagger services services.AddSwaggerDocument(); //API Versioning services.AddApiVersioning(o => { o.ReportApiVersions = true; o.AssumeDefaultVersionWhenUnspecified = true; o.DefaultApiVersion = new ApiVersion(1, 0); o.ApiVersionReader = ApiVersionReader.Combine( new QueryStringApiVersionReader(), new HeaderApiVersionReader("api-version") ); }); }
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //添加版本,可以Header和QueryString来区分 services.AddApiVersioning(cfg => { cfg.DefaultApiVersion = new ApiVersion(1, 1); cfg.AssumeDefaultVersionWhenUnspecified = true; cfg.ReportApiVersions = true; cfg.ApiVersionReader = ApiVersionReader.Combine(new HeaderApiVersionReader("X-Version"), new QueryStringApiVersionReader("v")); }); }
public void ConfigureServices(IServiceCollection services) { // Setup controllers services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = true; }); services.AddApiVersioning(options => { options.ApiVersionReader = ApiVersionReader.Combine( new QueryStringApiVersionReader("api-version"), new HeaderApiVersionReader("api-version")); options.DefaultApiVersion = ApiVersion.Parse("1.0"); options.AssumeDefaultVersionWhenUnspecified = true; // TODO: Use standard format for api exceptions }); // Setup config services.AddOptions(); services.Configure <DataStoreConfiguration>(_configuration.GetSection("DataStore")); // Setup logging + telemetry services.AddApplicationInsightsTelemetry(); // Add HTTP Client services.AddHttpClient(); // Setup database services.AddDbContext <FeInterventionsDbContext>(); services.AddScoped <IFeInterventionsDbContext, FeInterventionsDbContext>(); services.AddScoped <IFeProviderRepository, FeProviderRepository>(); services.AddScoped <ILearnerRepository, LearnerRepository>(); services.AddScoped <ILearningDeliveryRepository, LearningDeliveryRepository>(); // Add location service services.AddSingleton <ILocationService>(sp => { var httpClientFactory = sp.GetService <IHttpClientFactory>(); var httpClient = httpClientFactory.CreateClient(); var logger = sp.GetService <ILogger <PostcodesIoApiLocationService> >(); return(new PostcodesIoApiLocationService(httpClient, logger)); }); // Setup mapper services.AddAutoMapper(GetType().Assembly); // Setup application layer services.AddFeInterventionsManagers(); }
public static void Register(HttpConfiguration config) { // Web API configuration and services // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); config.Filters.Add(new ValidateModelAttribute()); config.Filters.Add(new ItemNotFoundExceptionFilterAttribute()); AutofacConfig.Register(); //Anti xss config config.Formatters.JsonFormatter.SerializerSettings.Converters = new List <JsonConverter> { new AntiXssConverter() }; config.Formatters.JsonFormatter.SerializerSettings.StringEscapeHandling = StringEscapeHandling.EscapeHtml; config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler()); //Avoid child auto reference config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; //Api versioning config.AddApiVersioning(cfg => { cfg.DefaultApiVersion = new Microsoft.Web.Http.ApiVersion(1, 0); cfg.AssumeDefaultVersionWhenUnspecified = true; cfg.ReportApiVersions = true; cfg.ApiVersionReader = ApiVersionReader.Combine(new HeaderApiVersionReader("X-Version")); }); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //WebApiThrottle, brute force protection config.MessageHandlers.Add(new ThrottlingHandler() { Policy = new ThrottlePolicy(perSecond: 5, perMinute: 30) { IpThrottling = true, ClientThrottling = true, EndpointThrottling = true }, Repository = new CacheRepository() }); }
public static void Register(HttpConfiguration config) { // Web API configuration and services AutofacConfig.Register(); config.AddApiVersioning(cfg => { cfg.DefaultApiVersion = new Microsoft.Web.Http.ApiVersion(1, 1); cfg.AssumeDefaultVersionWhenUnspecified = true; cfg.ReportApiVersions = true; // avoid URL versioning if possible# // cfg.ApiVersionReader = new UrlSegmentApiVersionReader(); // var constraintResolver = new DefaultInlineConstraintResolver() { // ConstraintMap = { // ["apiVersion"] = typeof(ApiVersionRouteConstraint); // } // Then in Routes (at class level if possible to simplify) // [RoutePrefix("api/v{version:apiVersion}/camps")] // and Urls are then like http://localhost:6600/api/v2.0/camps/ATL2018 //cfg.ApiVersionReader = new HeaderApiVersionReader("X-Version"); cfg.ApiVersionReader = ApiVersionReader.Combine( new HeaderApiVersionReader("X-Version"), new QueryStringApiVersionReader("ver")); // Conventions-based //cfg.Conventions.Controller<TalksController>() // .HasApiVersion(1, 0) // .HasApiVersion(1, 1) // .Action(m => m.Get(default(string), default(int), default(bool))) // .MapToApiVersion(2, 0); }); // change json case config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddApiVersioning(options => { options.DefaultApiVersion = new ApiVersion(1, 1); options.AssumeDefaultVersionWhenUnspecified = true; options.ReportApiVersions = true; options.ApiVersionReader = ApiVersionReader.Combine( new QueryStringApiVersionReader("v"), new HeaderApiVersionReader("v")); }); }
private void AddApiVersioning(IServiceCollection services) { services.AddApiVersioning(o => { o.ReportApiVersions = true; o.DefaultApiVersion = new ApiVersion(1, 0); o.AssumeDefaultVersionWhenUnspecified = true; o.ApiVersionReader = ApiVersionReader.Combine(new HeaderApiVersionReader("api-version"), new QueryStringApiVersionReader("api-version")); }).AddMvcCore().AddVersionedApiExplorer(option => { option.GroupNameFormat = "'v'VVV"; });; }
public static IServiceCollection ApiVersioning(this IServiceCollection services) { services.AddApiVersioning(options => { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0); options.ApiVersionReader = ApiVersionReader.Combine(new QueryStringApiVersionReader(), new HeaderApiVersionReader("api-version")); }); return(services); }