public void Parse_Unknown_Version_String_Should_Return_Unkown_Version() { var actual = ApiVersion.Parse("qwerty"); Assert.False(actual.IsKnown); Assert.Equal("qwerty", actual.Version); }
public void Empty_String_Should_Parse_To_Version_02() { var actual = ApiVersion.Parse(string.Empty); Assert.Same(actual, ApiVersion.Version_0_2_Or_Earlier); Assert.Equal(actual, ApiVersion.Version_0_2_Or_Earlier); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var mappingConfig = new MapperConfiguration(cfg => { cfg.AddProfile <WebMapperProfile>(); }); IMapper mapper = mappingConfig.CreateMapper(); services.AddSingleton(mapper); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Atacadista", Version = "v1", Description = "Exercício final openapi - aula arquitetura backend.", }); c.DescribeAllEnumsAsStrings(); }); services.AddApiVersioning(o => { o.ReportApiVersions = true; o.AssumeDefaultVersionWhenUnspecified = true; o.DefaultApiVersion = ApiVersion.Parse("1.0"); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddServiceDependency(); services.AddVaregistaAdapterDependency(Configuration.GetValue <string>("UrlVaregista")); }
/// <summary> /// Gets requested <see cref="ApiVersion"/> from a <see cref="HttpRequest"/>. /// </summary> public static ApiVersion GetRequestedVersion(this HttpRequest req) { if (req is null) { throw new ArgumentNullException(nameof(req)); } var versionText = req.Query[ApiVersion.QueryStringParamName]; if (StringValues.IsNullOrEmpty(versionText)) { if (req.Headers.TryGetValue(ApiVersion.HttpHeaderName, out var headerValues)) { if (headerValues.Any()) { versionText = headerValues.First(); } } } if (StringValues.IsNullOrEmpty(versionText)) { return(ApiVersion.DefaultVersion); } return(ApiVersion.Parse(versionText)); }
/// <summary> /// Called to apply the convention to the <see cref="T:Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerModel" />. /// </summary> /// <param name="controller">The <see cref="T:Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerModel" />.</param> public void Apply(ControllerModel controller) { var controllerVersion = controller.Selectors[0].AttributeRouteModel.Template.Split("/")[1]; var apiVersion = ApiVersion.Parse(controllerVersion); controller.ApiExplorer.GroupName = apiVersion.ToString(); }
public void ConfigureServices(IServiceCollection services) { services.AddApiVersioning( options => { options.DefaultApiVersion = ApiVersion.Parse("1"); options.RegisterMiddleware = true; options.AssumeDefaultVersionWhenUnspecified = true; options.ReportApiVersions = true; //por tipo de media //options.ApiVersionReader = new MediaTypeApiVersionReader("version"); //[header] Content-Type: application/json;version=x.x //por query string //options.ApiVersionReader = new QueryStringApiVersionReader("version"); //http://url.com/controller?version=x.x //por segmento de URL options.ApiVersionReader = new UrlSegmentApiVersionReader(); //[Route("[controller]/v{version:apiVersion}")] //por header //options.ApiVersionReader = new HeaderApiVersionReader("version"); //[header] version: x.x }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
/// <summary> /// Method for adding program services /// </summary> /// <param name="services"><see cref="IServiceCollection"/> instance</param> /// <returns><see cref="IServiceProvider"/> instance</returns> public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddApiVersioning(o => { o.ReportApiVersions = false; o.AssumeDefaultVersionWhenUnspecified = false; o.DefaultApiVersion = ApiVersion.Parse("1"); }); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddJsonOptions(x => x.SerializerSettings.Converters.Add(new StringEnumConverter())); services.AddSwaggerGen(cfg => { cfg.DescribeAllEnumsAsStrings(); cfg.SwaggerDoc("v1", new Info { Title = "10Manga", Version = "v1" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); cfg.IncludeXmlComments(xmlPath); }); services.AddResponseCompression(); return(AutofacContainer(services)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson(); services.AddVersionedApiExplorer( options => { options.GroupNameFormat = "'v'VVV"; options.SubstituteApiVersionInUrl = true; }); services.AddApiVersioning(options => { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = ApiVersion.Parse("1.0"); }); services.AddSwaggerGen(c => { c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { In = ParameterLocation.Header, Description = "Please insert JWT with Bearer into field", Name = "Authorization", Type = SecuritySchemeType.ApiKey, Scheme = "Bearer" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Name = "Authorization", Type = SecuritySchemeType.ApiKey, In = ParameterLocation.Header, Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, }, Array.Empty <string>() } }); c.SwaggerDoc("v1", new OpenApiInfo { Title = "Teste", Version = "v1" }); }); services.AddApplication(); services.AddTokenAdapter( Configuration.GetSafe <JwtConfiguration>()); }
public void Parse_Version_2019_01_30_Preview_Should_Return_Version() { var actual = ApiVersion.Parse("2019-01-30-preview"); Assert.True(actual.IsKnown); Assert.Equal(actual, ApiVersion.Version_2019_01_30_Preview); Assert.Same(actual, ApiVersion.Version_2019_01_30_Preview); }
public void Parse_Version_2018_12_16_Preview_Should_Return_Version() { var actual = ApiVersion.Parse("2018-12-16-preview"); Assert.True(actual.IsKnown); Assert.Equal(actual, ApiVersion.Version_2018_12_16_Preview); Assert.Same(actual, ApiVersion.Version_2018_12_16_Preview); }
/// <summary> /// Get function version from "api-version" response header /// </summary> /// <param name="response"></param> /// <returns></returns> private ApiVersion GetFunctionVersion(HttpResponseMessage response) { // if no version information is available in response header, log error. Validation failed! if (!response.Headers.TryGetValues(ApiVersion.HttpHeaderName, out var versionValues) || !versionValues.Any()) { return(ApiVersion.DefaultVersion); } return(ApiVersion.Parse(versionValues.FirstOrDefault(), returnAsKnown: true)); }
public void parse_should_throw_format_exception_for_invalid_text(string text, string message) { // arrange Action parse = () => ApiVersion.Parse(text); // act // assert parse.ShouldThrow <FormatException>().WithMessage(message); }
public void to_string_should_return_expected_string(string text) { // arrange var apiVersion = ApiVersion.Parse(text); // act var @string = apiVersion.ToString(); // assert @string.Should().Be(text); }
public void format_should_return_formatted_long_version_string(ApiVersionFormatProvider provider) { // arrange var apiVersion = ApiVersion.Parse("1-RC"); // act var minorVersion = provider.Format("VVVV", apiVersion, CurrentCulture); // assert minorVersion.Should().Be("1.0-RC"); }
public void format_should_return_full_formatted_string_with_optional_components(ApiVersionFormatProvider provider) { // arrange var apiVersion = ApiVersion.Parse("2017-05-01.1-Beta"); // act var format = provider.Format("FF", apiVersion, CurrentCulture); // assert format.Should().Be("2017-05-01.1.0-Beta"); }
public void to_string_with_format_should_return_expected_string(string format, string text, string formattedString) { // arrange var apiVersion = ApiVersion.Parse(text); // act var @string = apiVersion.ToString(format); // assert @string.Should().Be(formattedString); }
/// <summary> /// 修复版本号的显示 /// </summary> /// <param name="segment"></param> /// <returns></returns> private static string FixIfVersion(string segment) { if (segment.IsMatch(@"v\d_*\d*") == false) { return(segment); } var version = segment.Replace("_", ".").TrimStart('v'); return("v" + ApiVersion.Parse(version).ToString("VV")); }
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 IServiceCollection AddApiVersioning(this IServiceCollection services, VersioningConfigurationModel versioningConfiguration) { services.AddApiVersioning(opts => { opts.DefaultApiVersion = ApiVersion.Parse(versioningConfiguration.Default); opts.AssumeDefaultVersionWhenUnspecified = true; opts.ApiVersionReader = new UrlSegmentApiVersionReader(); opts.RouteConstraintName = versioningConfiguration.RouteConstraintName; }); return(services); }
public void api_version_comparisons_should_return_expected_result(string versionValue, string otherVersionValue, int expected) { // arrange var version = ApiVersion.Parse(versionValue); var otherVersion = ApiVersion.Parse(otherVersionValue); // act var result = version.CompareTo(otherVersion); // assert result.Should().Be(expected); }
public static IServiceCollection AddAuthApiVersioning(this IServiceCollection services) { services.AddApiVersioning(x => { x.DefaultApiVersion = ApiVersion.Parse(Constants.ApiV1); x.ReportApiVersions = true; x.ApiVersionReader = new UrlSegmentApiVersionReader(); x.ErrorResponses = new ApiVersioningErrorResponseProvider(); }); return(services); }
public void equals_override_should_return_true_when_api_versions_are_equal(string text) { // arrange var apiVersion = ApiVersion.Parse(text); object obj = ApiVersion.Parse(text); // act var equal = apiVersion.Equals(obj); // assert equal.Should().BeTrue(); }
public void X3DX3D_should_return_true_when_api_versions_are_equal(string text) { // arrange var v1 = ApiVersion.Parse(text); var v2 = ApiVersion.Parse(text); // act var equal = v1 == v2; // assert equal.Should().BeTrue(); }
/// <summary> Adds API versioning service with default configurations </summary> /// <param name="services"> The collection of DI registered services </param> /// <param name="defaultApiVersion"> The default version </param> public static void AddApiVersioning(this IServiceCollection services, string defaultApiVersion) { services.AddVersionedApiExplorer(options => { options.GroupNameFormat = "VV"; options.SubstituteApiVersionInUrl = true; options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = ApiVersion.Parse(defaultApiVersion); }); services.AddApiVersioning(options => options.ReportApiVersions = true); }
IEnumerable <ApiVersion> DeriveGroupVersion(ApiVersion apiVersion) { yield return(apiVersion); if (apiVersion.GroupVersion.HasValue) { yield return(new ApiVersion(apiVersion.GroupVersion.Value)); yield return(apiVersion.MinorVersion == null ? ApiVersion.Parse($"{apiVersion.MajorVersion}-{apiVersion.Status}") : new ApiVersion(apiVersion.MajorVersion.Value, apiVersion.MinorVersion.Value, apiVersion.Status)); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddControllers() .SetCompatibilityVersion(CompatibilityVersion.Latest) .AddNewtonsoftJson(); // sorry MS, this just does *more* services.AddApiVersioning(c => { c.AssumeDefaultVersionWhenUnspecified = true; c.DefaultApiVersion = ApiVersion.Parse("1.0"); }); services.AddVersionedApiExplorer(c => { c.GroupNameFormat = "'v'VV"; c.DefaultApiVersion = ApiVersion.Parse("1.0"); c.ApiVersionParameterSource = new UrlSegmentApiVersionReader(); c.SubstituteApiVersionInUrl = true; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1.0", new OpenApiInfo { Title = "PluralKit", Version = "1.0" }); c.EnableAnnotations(); c.AddSecurityDefinition("TokenAuth", new OpenApiSecurityScheme { Name = "Authorization", Type = SecuritySchemeType.ApiKey }); // Exclude routes without a version, then fall back to group name matching (default behavior) c.DocInclusionPredicate((docName, apiDesc) => { if (!apiDesc.RelativePath.StartsWith("v1/")) { return(false); } return(apiDesc.GroupName == docName); }); // Set the comments path for the Swagger JSON and UI. // https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1&tabs=visual-studio#customize-and-extend var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); services.AddSwaggerGenNewtonsoftSupport(); }
private static IServiceCollection AddSwagger(this IServiceCollection services, Action <SwaggerGenOptions> swaggerSetupAction = null) { services.AddMvcCore().AddVersionedApiExplorer((options => { options.DefaultApiVersion = ApiVersion.Parse("1.0"); options.SubstituteApiVersionInUrl = true; options.AssumeDefaultVersionWhenUnspecified = true; options.GroupNameFormat = "'v'VVV"; })); services.AddApiVersioning(); services.AddSwaggerGen(swaggerSetupAction); return(services); }
public void get_edm_model_should_retrieve_configured_model_by_api_version(int modelIndex, string apiVersionValue) { // arrange var apiVersion = ApiVersion.Parse(apiVersionValue); var configuration = new HttpConfiguration(); var models = CreateModels(configuration).ToArray(); configuration.MapVersionedODataRoutes("odata", "api", models); // act var model = configuration.GetEdmModel(apiVersion); // assert model.Should().BeSameAs(models[modelIndex]); }
public void select_controller_should_return_correct_controller_for_versioned_url(string versionSegment, Type controllerType, string actionName, string declaredVersionsValue) { // arrange var declared = declaredVersionsValue.Split(',').Select(v => ApiVersion.Parse(v)); var supported = new[] { new ApiVersion(1, 0), new ApiVersion(2, 0), new ApiVersion(3, 0), new ApiVersion(5, 0) }; var deprecated = new[] { new ApiVersion(4, 0) }; var implemented = supported.Union(deprecated).OrderBy(v => v).ToArray(); var requestUri = $"http://localhost/api/{versionSegment}/test"; var configuration = AttributeRoutingEnabledConfiguration; var request = new HttpRequestMessage(Get, requestUri); configuration.AddApiVersioning(); configuration.EnsureInitialized(); var routeData = configuration.Routes.GetRouteData(request); var requestContext = new HttpRequestContext { IsLocal = true, Configuration = configuration, RouteData = routeData, Url = new UrlHelper(request) }; request.SetConfiguration(configuration); request.SetRouteData(routeData); request.SetRequestContext(requestContext); var httpControllerSelector = configuration.Services.GetHttpControllerSelector(); var actionSelector = configuration.Services.GetActionSelector(); // act var controller = httpControllerSelector.SelectController(request); var context = new HttpControllerContext(requestContext, request, controller, controller.CreateController(request)); var action = actionSelector.SelectAction(context); // assert controller.ControllerType.Should().Be(controllerType); action.ActionName.Should().Be(actionName); controller.GetApiVersionModel().ShouldBeEquivalentTo( new { IsApiVersionNeutral = false, DeclaredApiVersions = declared, ImplementedApiVersions = implemented, SupportedApiVersions = supported, DeprecatedApiVersions = deprecated }); }
private void ConfigureApiVersioning(IServiceCollection services) { services.AddVersionedApiExplorer( options => { options.GroupNameFormat = "'v'VVV"; options.SubstituteApiVersionInUrl = true; }); services.AddApiVersioning(options => { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = ApiVersion.Parse(ApiMetadata.DefaultApiVersion); }); }