public static HttpConfiguration NewPeopleConfiguration() { var configuration = new HttpConfiguration(); var controllerTypeResolver = new ControllerTypeCollection( typeof(Simulators.V1.PeopleController), typeof(Simulators.V2.PeopleController), typeof(Simulators.V3.PeopleController)); var builder = new VersionedODataModelBuilder(configuration) { ModelConfigurations = { new PersonModelConfiguration() } }; var models = builder.GetEdmModels(); configuration.Services.Replace(typeof(IHttpControllerTypeResolver), controllerTypeResolver); configuration.AddApiVersioning(); configuration.MapVersionedODataRoutes("odata", "api/v{apiVersion}", models); return(configuration); }
public IEnumerable <IEdmModel> GetEdmModels(HttpConfiguration configuration) { var modelBuilder = new VersionedODataModelBuilder(configuration) { ModelBuilderFactory = () => new ODataConventionModelBuilder(), ModelConfigurations = { //new ApplicationDescriptionOdataModelBuilderConfiguration(), //new DataClassificationOdataModelBuilderConfiguration(), } }; foreach (var item in RegisterByReflectionTheODataModelDefinitions()) { modelBuilder.ModelConfigurations.Add(item); } return(modelBuilder.GetEdmModels()); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, VersionedODataModelBuilder modelBuilder ) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(builder => { builder.Select().Expand().Filter().OrderBy().Count().MaxTop(100); builder.MapVersionedODataRoutes("odata", "odata", modelBuilder.GetEdmModels()); }); }
static IEnumerable <IEdmModel> CreateModels(HttpConfiguration configuration) { var controllerTypeResolver = new Mock <IHttpControllerTypeResolver>(); var controllerTypes = new List <Type>() { typeof(ControllerV1), typeof(ControllerV2) }; controllerTypeResolver.Setup(ctr => ctr.GetControllerTypes(It.IsAny <IAssembliesResolver>())).Returns(controllerTypes); configuration.Services.Replace(typeof(IHttpControllerTypeResolver), controllerTypeResolver.Object); configuration.AddApiVersioning(); var builder = new VersionedODataModelBuilder(configuration) { DefaultModelConfiguration = (b, v, r) => b.EntitySet <TestEntity>("Tests"), }; return(builder.GetEdmModels()); }
public void Configuration(IAppBuilder appBuilder) { var configuration = new HttpConfiguration(); var httpServer = new HttpServer(configuration); configuration.AddApiVersioning( options => { // reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions" options.ReportApiVersions = true; // allows a client to make a request without specifying an api version. the value of // options.DefaultApiVersion will be 'assumed'; this is meant to grandfather in legacy apis options.AssumeDefaultVersionWhenUnspecified = true; // allow multiple locations to request an api version options.ApiVersionReader = ApiVersionReader.Combine( new QueryStringApiVersionReader(), new HeaderApiVersionReader("api-version", "x-ms-version")); }); var modelBuilder = new VersionedODataModelBuilder(configuration) { ModelConfigurations = { new PersonModelConfiguration(), new OrderModelConfiguration() } }; var models = modelBuilder.GetEdmModels(); var batchHandler = new DefaultODataBatchHandler(httpServer); // NOTE: when you mix OData and non-Data controllers in Web API, it's RECOMMENDED to only use // convention-based routing. using attribute routing may not work as expected due to limitations // in the underlying routing system. the order of route registration is important as well. // // DO NOT use configuration.MapHttpAttributeRoutes(); configuration.MapVersionedODataRoutes("odata", "api", models, ConfigureContainer, batchHandler); configuration.Routes.MapHttpRoute("orders", "api/{controller}/{id}", new { id = Optional }); appBuilder.UseWebApi(httpServer); }
public void Configuration(IAppBuilder appBuilder) { var configuration = new HttpConfiguration(); var httpServer = new HttpServer(configuration); configuration.AddApiVersioning( options => { // reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions" options.ReportApiVersions = true; // apply api versions using conventions rather than attributes options.Conventions.Controller <OrdersController>() .HasApiVersion(1, 0); options.Conventions.Controller <PeopleController>() .HasApiVersion(1, 0) .HasApiVersion(2, 0) .Action(c => c.Patch(default(int), null, null)).MapToApiVersion(2, 0); options.Conventions.Controller <People2Controller>() .HasApiVersion(3, 0); }); configuration.EnableCaseInsensitive(true); configuration.EnableUnqualifiedNameCall(true); var modelBuilder = new VersionedODataModelBuilder(configuration) { ModelBuilderFactory = () => new ODataConventionModelBuilder().EnableLowerCamelCase(), ModelConfigurations = { new PersonModelConfiguration(), new OrderModelConfiguration() } }; var models = modelBuilder.GetEdmModels(); var batchHandler = new DefaultODataBatchHandler(httpServer); configuration.MapVersionedODataRoutes("odata", "api", models, batchHandler); configuration.MapVersionedODataRoutes("odata-bypath", "v{apiVersion}", models, batchHandler); appBuilder.UseWebApi(httpServer); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, VersionedODataModelBuilder modelBuilder) { app.UseRouting(); app.UseEndpoints( endpoints => { endpoints.MapControllers(); // INFO: you do NOT and should NOT use both the query string and url segment methods together. // this configuration is merely illustrating that they can coexist and allows you to easily // experiment with either configuration. one of these would be removed in a real application. // // INFO: only pass the route prefix to GetEdmModels if you want to split the models; otherwise, both routes contain all models // WHEN VERSIONING BY: query string, header, or media type endpoints.MapVersionedODataRoute("odata", "api", modelBuilder); // WHEN VERSIONING BY: url segment endpoints.MapVersionedODataRoute("odata-bypath", "api/v{version:apiVersion}", modelBuilder); }); }
public void Configuration(IAppBuilder appBuilder) { var configuration = new HttpConfiguration(); var httpServer = new HttpServer(configuration); configuration.MapHttpAttributeRoutes(); configuration.AddApiVersioning( o => { o.ReportApiVersions = true; o.AssumeDefaultVersionWhenUnspecified = true; o.ApiVersionReader = new QueryStringOrHeaderApiVersionReader() { HeaderNames = { "api-version", "x-ms-version" } }; }); configuration.EnableCaseInsensitive(true); configuration.EnableUnqualifiedNameCall(true); var modelBuilder = new VersionedODataModelBuilder(configuration) { ModelBuilderFactory = () => new ODataConventionModelBuilder().EnableLowerCamelCase(), ModelConfigurations = { new PersonModelConfiguration(), new OrderModelConfiguration() } }; var models = modelBuilder.GetEdmModels(); var batchHandler = new DefaultODataBatchHandler(httpServer); configuration.MapVersionedODataRoutes("odata", "api", models, batchHandler); configuration.Routes.MapHttpRoute("orders", "api/{controller}/{id}", new { id = Optional }); appBuilder.UseWebApi(httpServer); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, VersionedODataModelBuilder modelBuilder) { app .UseResponseCompression() .UseForwardedHeaders() .UseWhen(ctx => ctx.Request.Path.Value.StartsWith("/issue599/v"), api => { api .UseCors(policy => policy .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); }) .UseMvc(route => route .SetUrlKeyDelimiter(ODataUrlKeyDelimiter.Parentheses) .MapVersionedODataRoute( "odata", "issue599/v{version:apiVersion}", modelBuilder.GetEdmModels())) .UseSwagger() .UseSwaggerUI(); }
protected AdvancedAcceptanceTest() { FilteredControllerTypes.Add(typeof(OrdersController)); FilteredControllerTypes.Add(typeof(Orders2Controller)); FilteredControllerTypes.Add(typeof(Orders3Controller)); FilteredControllerTypes.Add(typeof(PeopleController)); FilteredControllerTypes.Add(typeof(People2Controller)); Configuration.MapHttpAttributeRoutes(); Configuration.AddApiVersioning( options => { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = true; options.ApiVersionReader = new QueryStringOrHeaderApiVersionReader() { HeaderNames = { "api-version", "x-ms-version" } }; }); var modelBuilder = new VersionedODataModelBuilder(Configuration) { ModelBuilderFactory = () => new ODataConventionModelBuilder().EnableLowerCamelCase(), ModelConfigurations = { new PersonModelConfiguration(), new OrderModelConfiguration(supportedApiVersion: new ApiVersion(2, 0)) } }; var models = modelBuilder.GetEdmModels(); Configuration.MapVersionedODataRoutes("odata", "api", models); Configuration.Routes.MapHttpRoute("orders", "api/{controller}/{key}", new { key = Optional }); Configuration.EnsureInitialized(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, VersionedODataModelBuilder modelBuilder) { app.UseMvc( routeBuilder => { routeBuilder.EnableDependencyInjection(); // the following will not work as expected // BUG: https://github.com/OData/WebApi/issues/1837 // routeBuilder.SetDefaultODataOptions( new ODataOptions() { UrlKeyDelimiter = Parentheses } ); routeBuilder.ServiceProvider.GetRequiredService <ODataOptions>().UrlKeyDelimiter = Parentheses; // global odata query options routeBuilder.Count(); routeBuilder.MapVersionedODataRoutes("odata", "api", modelBuilder.GetEdmModels()); }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); // app.UseEndpoints(endpoints => // { // endpoints.MapControllers(); // endpoints.EnableDependencyInjection(); // }); }
public static IApplicationBuilder UseODataVersioningSwaggerDocumentation(this IApplicationBuilder app, VersionedODataModelBuilder modelBuilder, IApiVersionDescriptionProvider provider) { // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI( options => { foreach (var description in provider.ApiVersionDescriptions) { options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant()); } // options.RoutePrefix = string.Empty; // To serve the Swagger UI at the app's root (http://localhost:<port>/), set the RoutePrefix property to an empty string }); return(app); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, VersionedODataModelBuilder modelBuilder) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAspNetBoilerPlate v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.EnableDependencyInjection(); endpoints.Select().Expand().Filter().OrderBy().Count().MaxTop(10); }); }
public async Task options_should_return_expected_headers() { // arrange var configuration = new HttpConfiguration(); var builder = new VersionedODataModelBuilder(configuration); var metadata = new VersionedMetadataController() { Configuration = configuration }; var controllerTypeResolver = new Mock <IHttpControllerTypeResolver>(); var controllerTypes = new List <Type>() { typeof(Controller1), typeof(Controller2), typeof(VersionedMetadataController) }; controllerTypeResolver.Setup(ctr => ctr.GetControllerTypes(It.IsAny <IAssembliesResolver>())).Returns(controllerTypes); configuration.Services.Replace(typeof(IHttpControllerTypeResolver), controllerTypeResolver.Object); configuration.AddApiVersioning(); var models = builder.GetEdmModels(); var request = new HttpRequestMessage(new HttpMethod("OPTIONS"), "http://localhost/$metadata"); var response = default(HttpResponseMessage); configuration.MapVersionedODataRoutes("odata", null, models); using (var server = new HttpServer(configuration)) using (var client = new HttpClient(server)) { // act response = (await client.SendAsync(request)).EnsureSuccessStatusCode(); } // assert response.Headers.GetValues("OData-Version").Single().Should().Be("4.0"); response.Headers.GetValues("api-supported-versions").Single().Should().Be("1.0, 2.0, 3.0"); response.Headers.GetValues("api-deprecated-versions").Single().Should().Be("3.0-Beta"); response.Content.Headers.Allow.Should().BeEquivalentTo("GET", "OPTIONS"); }
public void Configuration(IAppBuilder appBuilder) { var configuration = new HttpConfiguration(); var httpServer = new HttpServer(configuration); // reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions" configuration.AddApiVersioning(o => o.ReportApiVersions = true); var modelBuilder = new VersionedODataModelBuilder(configuration) { ModelConfigurations = { new PersonModelConfiguration(), new OrderModelConfiguration() } }; var models = modelBuilder.GetEdmModels(); var batchHandler = new DefaultODataBatchHandler(httpServer); configuration.MapVersionedODataRoutes("odata", "api", models, ConfigureContainer, batchHandler); configuration.MapVersionedODataRoutes("odata-bypath", "v{apiVersion}", models, ConfigureContainer); appBuilder.UseWebApi(httpServer); }
protected BasicAcceptanceTest() { FilteredControllerTypes.Add(typeof(OrdersController)); FilteredControllerTypes.Add(typeof(PeopleController)); FilteredControllerTypes.Add(typeof(People2Controller)); Configuration.AddApiVersioning(options => options.ReportApiVersions = true); var modelBuilder = new VersionedODataModelBuilder(Configuration) { ModelBuilderFactory = () => new ODataConventionModelBuilder().EnableLowerCamelCase(), ModelConfigurations = { new PersonModelConfiguration(), new OrderModelConfiguration() } }; var models = modelBuilder.GetEdmModels(); Configuration.MapVersionedODataRoutes("odata", "api", models); Configuration.MapVersionedODataRoutes("odata-bypath", "v{apiVersion}", models); Configuration.EnsureInitialized(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure( IApplicationBuilder app, VersionedODataModelBuilder modelBuilder, IApiVersionDescriptionProvider provider) { app.UseRouting(); app.UseCors(); app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints( endpoints => { // global odata query options endpoints.Count(); // the following will not work as expected // BUG: https://github.com/OData/WebApi/issues/1837 // endpoints.SetDefaultODataOptions( // new ODataOptions() { UrlKeyDelimiter = Parentheses } ); // endpoints // .ServiceProvider // .GetRequiredService<ODataOptions>() // .UrlKeyDelimiter = ODataUrlKeyDelimiter.Parentheses; // register routes with and without the api version constraint endpoints.MapVersionedODataRoute( "explicit", "api/v{version:apiVersion}", modelBuilder); endpoints.MapVersionedODataRoute("odata", "api", modelBuilder); }); ConfigureSwaggerUI(app, provider); }
public BasicFixture() { FilteredControllerTypes.Add(typeof(OrdersController)); FilteredControllerTypes.Add(typeof(PeopleController)); FilteredControllerTypes.Add(typeof(People2Controller)); FilteredControllerTypes.Add(typeof(CustomersController)); Configuration.AddApiVersioning(options => options.ReportApiVersions = true); var modelBuilder = new VersionedODataModelBuilder(Configuration) { ModelConfigurations = { new PersonModelConfiguration(), new OrderModelConfiguration(), new CustomerModelConfiguration(), } }; var models = modelBuilder.GetEdmModels(); Configuration.MapVersionedODataRoute("odata", "api", models); Configuration.MapVersionedODataRoute("odata-bypath", "v{apiVersion}", models); Configuration.EnsureInitialized(); }
public void Configuration(IAppBuilder builder) { var configuration = new HttpConfiguration(); var httpServer = new HttpServer(configuration); var batchHandler = new DefaultODataBatchHandler(httpServer); configuration.AddApiVersioning(options => options.ReportApiVersions = true); var modelBuilder = new VersionedODataModelBuilder(configuration) { ModelConfigurations = { new DataModelConfiguration() } }; var models = modelBuilder.GetEdmModels(); configuration.MapVersionedODataRoutes("odata", "data/v{apiVersion}", models, ConfigureContainer, batchHandler); var apiExplorer = configuration.AddODataApiExplorer( options => { options.GroupNameFormat = "'v'VVV"; options.SubstituteApiVersionInUrl = true; }); builder.UseWebApi(httpServer); }
/// <summary> /// Configures the o data. /// </summary> /// <param name="app">The application.</param> public static void ConfigureOData(IAppBuilder app) { //HttpConfig.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Web-API-Konfiguration und -Dienste HttpConfig.Select() .Filter() .OrderBy() .MaxTop(null) .Count(); var httpServer = new HttpServer(HttpConfig); var modelBuilder = new VersionedODataModelBuilder(HttpConfig) { ModelBuilderFactory = () => new ODataConventionModelBuilder(), ModelConfigurations = { new NVEntitySetConfiguration <NVArticle>(), new NVConfiguration() } }; HttpConfig.MapVersionedODataRoutes("odata", "", modelBuilder.GetEdmModels(), new DefaultODataBatchHandler(httpServer)); }
protected BasicAcceptanceTest() { FilteredControllerTypes.Add(typeof(OrdersController)); FilteredControllerTypes.Add(typeof(PeopleController)); FilteredControllerTypes.Add(typeof(People2Controller)); FilteredControllerTypes.Add(typeof(CustomersController)); Configuration.AddApiVersioning(options => options.ReportApiVersions = true); var modelBuilder = new VersionedODataModelBuilder(Configuration) { ModelConfigurations = { new PersonModelConfiguration(), new OrderModelConfiguration(), new CustomerModelConfiguration(), } }; var models = modelBuilder.GetEdmModels(); Configuration.MapVersionedODataRoutes("odata", "api", models, builder => builder.AddService(Singleton, typeof(ODataUriResolver), sp => TestUriResolver)); Configuration.MapVersionedODataRoutes("odata-bypath", "v{apiVersion}", models, builder => builder.AddService(Singleton, typeof(ODataUriResolver), sp => TestUriResolver)); Configuration.EnsureInitialized(); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, VersionedODataModelBuilder modelBuilder, IApiVersionDescriptionProvider provider) { var models = modelBuilder.GetEdmModels(); app.UseAuthentication(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { var errorFeature = context.Features.Get <IExceptionHandlerPathFeature>(); var exception = errorFeature.Error; var path = errorFeature.Path; var problemDetails = new ProblemDetails { Instance = $"urn:my:error:{Guid.NewGuid()}", Detail = exception.Message }; if (exception is BadHttpRequestException) { problemDetails.Title = "Invalid request!"; problemDetails.Status = StatusCodes.Status400BadRequest; } else { problemDetails.Title = "An unexpected error occurred!"; problemDetails.Status = StatusCodes.Status500InternalServerError; } context.Response.ContentType = "application/problem+json"; context.Response.StatusCode = problemDetails.Status.Value; await context.Response.WriteAsync(JsonSerializer.Serialize(problemDetails)); }); }); } app.UseMvc(routes => { routes.ServiceProvider.GetRequiredService <ODataOptions>().UrlKeyDelimiter = ODataUrlKeyDelimiter.Parentheses; routes.Select().Filter().Expand().OrderBy().Count(); routes.MapVersionedODataRoutes("odata", "odata/v{version:apiVersion}", models); routes.EnableDependencyInjection(); routes.MapRoute("api", "{controller=Home}/{action=Index}"); }); if (env.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(options => { foreach (var description in provider.ApiVersionDescriptions) { options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant()); } }); } }
public void Configure(IApplicationBuilder app, VersionedODataModelBuilder builder) { app.UseMvc(r => r.MapVersionedODataRoutes("odata", null, builder.GetEdmModels())); }
/// <summary> /// Configures the application using the provided builder. /// </summary> /// <param name="builder">The current application builder.</param> public void Configuration(IAppBuilder builder) { var configuration = new HttpConfiguration(); var httpServer = new HttpServer(configuration); //// reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions" configuration.AddApiVersioning(options => options.ReportApiVersions = true); //// note: this is required to make the default swagger json settings match the odata conventions applied by EnableLowerCamelCase() configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //-----DATA V1----- var modelBuilder = new VersionedODataModelBuilder(configuration) { ModelConfigurations = { new Data.V1.DataModelConfiguration() } }; var models = modelBuilder.GetEdmModels(); configuration.MapVersionedODataRoutes("odata-data-v1", "data/v{apiVersion}", models, ConfigureContainer); //-----DATA V2----- modelBuilder = new VersionedODataModelBuilder(configuration) { ModelConfigurations = { new Data.V2.DataModelConfiguration() } }; models = modelBuilder.GetEdmModels(); configuration.MapVersionedODataRoutes("odata-data-v2", "data/v{apiVersion}", models, ConfigureContainer); //-----CONFIG V11----- modelBuilder = new VersionedODataModelBuilder(configuration) { ModelConfigurations = { new Config.V11.ConfigModelConfiguration() } }; models = modelBuilder.GetEdmModels(); configuration.MapVersionedODataRoutes("odata-config-v11", "config/v{apiVersion}", models, ConfigureContainer); //-----CONFIG V12----- modelBuilder = new VersionedODataModelBuilder(configuration) { ModelConfigurations = { new Config.V12.ConfigModelConfiguration() } }; models = modelBuilder.GetEdmModels(); configuration.MapVersionedODataRoutes("odata-config-v12", "config/v{apiVersion}", models, ConfigureContainer); // add the versioned IApiExplorer and capture the strongly-typed implementation (e.g. ODataApiExplorer vs IApiExplorer) // note: the specified format code will format the version as "'v'major[.minor][-status]" var apiExplorer = configuration.AddODataApiExplorer( 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; // configure query options (which cannot otherwise be configured by OData conventions) // options.QueryOptions.Controller<Values.V1.Controllers.ValuesController>() // .Action(c => c.Get(default)).Allow(AllowedQueryOptions.Skip | AllowedQueryOptions.Count).AllowTop(100); //options.QueryOptions.Controller<Values.V2.Controllers.ValuesController>() // .Action(c => c.Get(default)).Allow(AllowedQueryOptions.Skip | AllowedQueryOptions.Count).AllowTop(100); }); //configuration.EnableSwagger( // "doc/{apiVersion}/swagger", // sConf => { // sConf.CustomProvider((defaultProvider) => { // return new ODataSwaggerProvider(defaultProvider, sConf, configuration) // .Configure((oDataConf) => { // //oDataConf.EnableSwaggerRequestCaching(); // oDataConf.IncludeNavigationProperties(); // }); // }); // // build a swagger document and endpoint for each discovered API version // sConf.MultipleApiVersions( // (apiDescription, version) => apiDescription.GetGroupName() == version, // info => { // foreach (var group in apiExplorer.ApiDescriptions) { // var description = "A sample application."; // if (group.IsDeprecated) { // description += " This API version has been deprecated."; // } // info.Version(group.Name, $"Sample API {group.ApiVersion}") // .Contact(c => c.Name("Alsic BVBA") // .Email("*****@*****.**")) // .Description(description); // } // }); // // add a custom operation filter which documents the implicit API version parameter // sConf.OperationFilter<SwaggerDefaultValues>(); // // integrate xml comments // sConf.IncludeXmlComments(XmlCommentsFilePath); // }) // .EnableSwaggerUi(swagger => swagger.EnableDiscoveryUrlSelector()); builder.UseWebApi(httpServer); }
/// <summary> /// Configures the application using the provided builder. /// </summary> /// <param name="builder">The current application builder.</param> public void Configuration(IAppBuilder builder) { var configuration = new HttpConfiguration(); var httpServer = new HttpServer(configuration); // reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions" configuration.AddApiVersioning(o => o.ReportApiVersions = true); var modelBuilder = new VersionedODataModelBuilder(configuration) { ModelBuilderFactory = () => new ODataConventionModelBuilder().EnableLowerCamelCase(), ModelConfigurations = { new PersonModelConfiguration(), new OrderModelConfiguration() } }; var models = modelBuilder.GetEdmModels(); configuration.MapVersionedODataRoutes("odata", "api", models, ConfigureODataServices); configuration.MapVersionedODataRoutes("odata-bypath", "api/v{apiVersion}", models, ConfigureODataServices); // add the versioned IApiExplorer and capture the strongly-typed implementation (e.g. ODataApiExplorer vs IApiExplorer) // note: the specified format code will format the version as "'v'major[.minor][-status]" var apiExplorer = configuration.AddODataApiExplorer(o => o.GroupNameFormat = "'v'VVV"); configuration.EnableSwagger( "{apiVersion}/swagger", swagger => { // build a swagger document and endpoint for each discovered API version swagger.MultipleApiVersions( (apiDescription, version) => apiDescription.GetGroupName() == version, info => { foreach (var group in apiExplorer.ApiDescriptions) { var description = "A sample application with Swagger, Swashbuckle, OData, and API versioning."; if (group.IsDeprecated) { description += " This API version has been deprecated."; } info.Version(group.Name, $"Sample API {group.ApiVersion}") .Contact(c => c.Name("Bill Mei").Email("*****@*****.**")) .Description(description) .License(l => l.Name("MIT").Url("https://opensource.org/licenses/MIT")) .TermsOfService("Shareware"); } }); // add a custom operation filter which documents the implicit API version parameter swagger.OperationFilter <SwaggerDefaultValues>(); // integrate xml comments swagger.IncludeXmlComments(XmlCommentsFilePath); }) .EnableSwaggerUi(swagger => swagger.EnableDiscoveryUrlSelector()); builder.UseWebApi(httpServer); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, VersionedODataModelBuilder modelBuilder) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseMvc( routeBuilder => { var models = modelBuilder.GetEdmModels(); routeBuilder.MapVersionedODataRoutes("odata", "api", models); routeBuilder.MapVersionedODataRoutes("odata-bypath", "v{version:apiVersion}", models); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, WordHintDbContext db , VersionedODataModelBuilder modelBuilder , IApiVersionDescriptionProvider provider ) { app.UseForwardedHeaders(); if (env.IsDevelopment()) { app.UseRequestResponseLogging(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } // app.UseHttpsRedirection(); // disable to use within docker behind a proxy app.UseStaticFiles(); app.UseCookiePolicy(); // You would either call EnsureCreated() or Migrate(). // EnsureCreated() is an alternative that completely skips the migrations pipeline and just creates a database that matches you current model. // It's good for unit testing or very early prototyping, when you are happy just to delete and re-create the database when the model changes. // db.Database.EnsureDeleted(); // db.Database.EnsureCreated(); // Note! Therefore don't use EnsureDeleted() and EnsureCreated() but Migrate(); db.Database.Migrate(); app.UseCors("Everything"); app.UseAuthentication(); // add signalr hub url app.UseSignalR(routes => { routes.MapHub <CrossWordSignalRHub>("/crosswordsignalrhub"); }); // Add support for OData to MVC pipeline var models = modelBuilder.GetEdmModels(); // versioning API // var model = WordModelConfiguration.GetEdmModel(new ODataConventionModelBuilder()); // single odata API app.UseMvc(routes => { // routes.MapRoute( // name: "default", // template: "{controller=Home}/{action=Index}/{id?}"); // setup odata filters routes.Select().Expand().Filter().OrderBy().MaxTop(300).Count(); // version with query parameter routes.MapVersionedODataRoutes( routeName: "odata", routePrefix: "odata", models: models); // version by path // routes.MapVersionedODataRoutes( // routeName: "odata-bypath", // routePrefix: "odata/v{version:apiVersion}", // models: models); // setup non-versioned odata route // routes.MapODataServiceRoute("odata", "odata", model); // Error: Cannot find the services container for the non-OData route. // This can occur when using OData components on the non-OData route and is usually a configuration issue. // Call EnableDependencyInjection() to enable OData components on non-OData routes. // This may also occur when a request was mistakenly handled by the ASP.NET Core routing layer instead of the OData routing layer, // for instance the URL does not include the OData route prefix configured via a call to MapODataServiceRoute(). // Workaround: https://github.com/OData/WebApi/issues/1175 // routes.EnableDependencyInjection(); }); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), app.UseODataVersioningSwaggerDocumentation(modelBuilder, provider); // app.UseSwaggerDocumentation(); }
/// <summary> /// Configures the application using the provided builder. /// </summary> /// <param name="builder">The current application builder.</param> public void Configuration(IAppBuilder builder) { const string routePrefix = default(string); var configuration = new HttpConfiguration(); var httpServer = new HttpServer(configuration); // reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions" configuration.AddApiVersioning(o => o.ReportApiVersions = true); // note: this is required to make the default swagger json settings match the odata conventions applied by EnableLowerCamelCase() configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); var modelBuilder = new VersionedODataModelBuilder(configuration) { ModelBuilderFactory = () => new ODataConventionModelBuilder().EnableLowerCamelCase(), ModelConfigurations = { new AllConfigurations(), new PersonModelConfiguration(), new OrderModelConfiguration(), } }; var models = modelBuilder.GetEdmModels(); // TODO: while you can use both, you should choose only ONE of the following; comment, uncomment, or remove as necessary // WHEN VERSIONING BY: query string, header, or media type configuration.MapVersionedODataRoutes("odata", routePrefix, models, ConfigureODataServices); // WHEN VERSIONING BY: url segment // configuration.MapVersionedODataRoutes( "odata-bypath", "api/v{apiVersion}", models, ConfigureODataServices ); // add the versioned IApiExplorer and capture the strongly-typed implementation (e.g. ODataApiExplorer vs IApiExplorer) // note: the specified format code will format the version as "'v'major[.minor][-status]" var apiExplorer = configuration.AddODataApiExplorer(o => o.GroupNameFormat = "'v'VVV"); configuration.EnableSwagger( "{apiVersion}/swagger", swagger => { // build a swagger document and endpoint for each discovered API version swagger.MultipleApiVersions( (apiDescription, version) => apiDescription.GetGroupName() == version, info => { foreach (var group in apiExplorer.ApiDescriptions) { var description = "A sample application with Swagger, Swashbuckle, OData, and API versioning."; if (group.IsDeprecated) { description += " This API version has been deprecated."; } info.Version(group.Name, $"Sample API {group.ApiVersion}") .Contact(c => c.Name("Bill Mei").Email("*****@*****.**")) .Description(description) .License(l => l.Name("MIT").Url("https://opensource.org/licenses/MIT")) .TermsOfService("Shareware"); } }); // add a custom operation filter which documents the implicit API version parameter swagger.OperationFilter <SwaggerDefaultValues>(); // integrate xml comments swagger.IncludeXmlComments(XmlCommentsFilePath); }) .EnableSwaggerUi(swagger => swagger.EnableDiscoveryUrlSelector()); builder.UseWebApi(httpServer); }
public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env, VersionedODataModelBuilder modelBuilder, IApiVersionDescriptionProvider provider) { if (env.IsDevelopment()) { _ = app.UseDeveloperExceptionPage(); } else { _ = app.UseHsts(); } _ = app.UseAuthentication() .UseAuthorization(); _ = app .UseMvc(routeBuilder => { var models = modelBuilder.GetEdmModels().ToList(); var singleton = Microsoft.OData.ServiceLifetime.Singleton; _ = routeBuilder .SetTimeZoneInfo(TimeZoneInfo.Utc) .Select() .Expand() .OrderBy() .MaxTop(100) .Filter() .Count() .MapVersionedODataRoutes("odata-bypath", "odata/v{version:apiVersion}", models, oBuilder => { _ = oBuilder.AddService <ODataSerializerProvider, NrsrxODataSerializerProvider>(singleton); }); }) .UseSwagger() .UseSwaggerUI(options => { foreach (var description in provider.ApiVersionDescriptions) { options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant()); } options.RoutePrefix = string.Empty; options.OAuthClientId(Configuration.GetValue <string>("SwaggerClientId")); options.OAuthAppName(Configuration.GetValue <string>("SwaggerAppName")); }); }
public override void Configure(IApplicationBuilder app, IWebHostEnvironment env, VersionedODataModelBuilder modelBuilder, IApiVersionDescriptionProvider provider) { modelBuilder.ModelConfigurations.Add(new TModelConfiguration()); TestContext = app.ApplicationServices.GetService <TestContext>(); _ = app.UseTestContextRequestLogger(TestContext); base.Configure(app, env, modelBuilder, provider); }