ApiVersionReader

We found 10 examples in language CSharp for this search. You will see 24 fragments of code.

Other methods


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddApiVersioning(options =>
            {
                options.DefaultApiVersion = ApiVersion.Default;
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.ReportApiVersions = true;
                options.ApiVersionReader = ApiVersionReader.Combine(
                    new QueryStringApiVersionReader("version"),
                    new MediaTypeApiVersionReader("version"),
                    new HeaderApiVersionReader("X-Version"));
                //options.ApiVersionReader = new QueryStringApiVersionReader("version");
                //options.ApiVersionReader = new MediaTypeApiVersionReader("version");
                //options.ApiVersionReader = new HeaderApiVersionReader("X-Version");
            });

            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<CampContext>();
            services.AddScoped<ICampRepository, CampRepository>();
            services.AddAutoMapper(Assembly.GetExecutingAssembly());
            services.AddApiVersioning(opt =>
            {
                opt.DefaultApiVersion = new ApiVersion(1, 1);
                opt.ReportApiVersions = true;
                opt.AssumeDefaultVersionWhenUnspecified = true;
                //opt.ApiVersionReader = ApiVersionReader.Combine(
                //    new HeaderApiVersionReader("X-Version"),
                //    new QueryStringApiVersionReader("ver", "version"));
                opt.ApiVersionReader = new UrlSegmentApiVersionReader();
            });
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(cfg =>
            {
                cfg.MapControllers();
            });
        }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<CampContext>();
        services.AddScoped<ICampRepository, CampRepository>();

        services.AddAutoMapper(Assembly.GetExecutingAssembly());

        services.AddControllers();

            services.AddApiVersioning(opt =>
            {
                opt.AssumeDefaultVersionWhenUnspecified = true;
                opt.DefaultApiVersion = new ApiVersion(1, 1);
                opt.ReportApiVersions = true;
                //opt.ApiVersionReader = new QueryStringApiVersionReader("ver");
                //opt.ApiVersionReader = new HeaderApiVersionReader("X-Version");
                opt.ApiVersionReader = ApiVersionReader.Combine( 
                    new HeaderApiVersionReader("X-Version"),
                    new QueryStringApiVersionReader("ver", "version")
                    );

                // NOT sure if this still work
                //opt.Conventions.Controller<TalksController>()
                //.HasApiVersion(new ApiVersion(1, 0));
            });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }

      app.UseRouting();

      app.UseAuthentication();
      app.UseAuthorization();

      app.UseEndpoints(cfg =>
      {
        cfg.MapControllers();
      });
    }


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Register Application Db Context
            services.AddDbContext<CampContext>();

            services.AddScoped<ICampRepository, CampRepository>();

            // Add AutoMapper
            services.AddAutoMapper(Assembly.GetExecutingAssembly());

            // Add API Versioning
            // Required in ASPNET CORE >=2.2 
            services.AddApiVersioning(opt =>
            {
                opt.AssumeDefaultVersionWhenUnspecified = true; // Assume a default version if not specified (1.1)
                opt.DefaultApiVersion = new ApiVersion(1, 1); // Default version is 1,1 (1.1)
                opt.ReportApiVersions = true; // Add headers to responses to say what API versions are gonna be supported by a certain URI

                // Version with headers
                /** 
                opt.ApiVersionReader = new QueryStringApiVersionReader("ver"); // Figure out how to determine the version from some part of the request
                opt.ApiVersionReader = new HeaderApiVersionReader("X-Version"); // Key => Value (Header parameter) where key is "X-Version" 
                **/

                // Using Multiple Versioning Methods
                // Calling ApiVersionReader as a static class...
                opt.ApiVersionReader = ApiVersionReader.Combine(
                    new HeaderApiVersionReader("X-Version"),
                    new QueryStringApiVersionReader("ver", "version", "api-version"),
                    new UrlSegmentApiVersionReader()
                );

                // Versioning with URL
                // opt.ApiVersionReader = new UrlSegmentApiVersionReader();

                // Versioning By Conventions
                // opt.Conventions.Controller<TalksController>()
                //     .HasApiVersion(new ApiVersion(1, 0))
                //     .HasApiVersion(new ApiVersion(1, 1))
                //     .Action(c => c.Delete(default(string), default(int)))
                //     .MapToApiVersion(1, 1);

            });

            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

        public static void AddSbContext(this IServiceCollection services, IConfiguration Configuration)
        {

            services.AddDbContext<ApplicationDbContext>(Options =>
            {
                Options.UseSqlServer((Configuration.GetConnectionString("DefaultConnection")));
            });
        }

        public static void AddElmah(this IServiceCollection services, IConfiguration Configuration, SiteSettings _siteSetting)
        {
            services.AddElmah<SqlErrorLog>(options =>
            {
                options.Path = _siteSetting.ElmahPath;
                options.ConnectionString = Configuration.GetConnectionString("ElmahError");
            });

        }

        public static void AddCorsExtention(this IServiceCollection services)
        {
            // add "ClientDomain": "https://www.tabandesign.ir" in appsetting.json
            // add app.UseCors("SiteCorsPolicy"); in Configure method

            var corsBuilder = new CorsPolicyBuilder();
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            //corsBuilder.WithOrigins("https://www.tabandesign.ir"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowAnyOrigin(); // For anyone access.
            corsBuilder.AllowCredentials();
            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }

        public static void AddMinimalMvc(this IServiceCollection services)
        {
            services.AddMvcCore()
            .AddApiExplorer()
            .AddAuthorization()
            .AddFormatterMappings()
            .AddDataAnnotations()
            .AddJsonFormatters()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        public static void AddJwtAuthentication(this IServiceCollection services, JwtSettings jwtSettings)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                var secretkey = Encoding.UTF8.GetBytes(jwtSettings.SecretKey);
                var encryptionkey = Encoding.UTF8.GetBytes(jwtSettings.Encryptkey);

                var validationParameters = new TokenValidationParameters
                {
                    ClockSkew = TimeSpan.Zero, // default: 5 min
                    RequireSignedTokens = true,

                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(secretkey),

                    RequireExpirationTime = true,
                    ValidateLifetime = true,

                    ValidateAudience = true, //default : false
                    ValidAudience = jwtSettings.Audience,

                    ValidateIssuer = true, //default : false
                    ValidIssuer = jwtSettings.Issuer,

                    TokenDecryptionKey = new SymmetricSecurityKey(encryptionkey)
                };

                options.RequireHttpsMetadata = false;
                options.SaveToken = true;
                options.TokenValidationParameters = validationParameters;
                options.Events = new JwtBearerEvents
                {
                    OnTokenValidated = async context =>
                    {
                        bool UpdateLastLogin = true;
                        var signInManager = context.HttpContext.RequestServices.GetRequiredService<SignInManager<User>>();
                        var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();

                        var claimsIdentity = context.Principal.Identity as ClaimsIdentity;
                        if (claimsIdentity.Claims?.Any() != true)
                            context.Fail("This token has no claims.");

                        var securityStamp = claimsIdentity.FindFirstValue(new ClaimsIdentityOptions().SecurityStampClaimType);
                        if (!securityStamp.HasValue())
                        {
                            context.Fail("This token has no secuirty stamp");
                            UpdateLastLogin = false;
                        }

                        //Find user and token from database and perform your custom validation
                        var userId = claimsIdentity.GetUserId<int>();
                        var user = await userRepository.GetByIdAsync(context.HttpContext.RequestAborted, userId);

                        //if (user.SecurityStamp != Guid.Parse(securityStamp))
                        //    context.Fail("Token secuirty stamp is not valid.");

                        var validatedUser = await signInManager.ValidateSecurityStampAsync(context.Principal);
                        if (validatedUser == null)
                        {
                            context.Fail("Token secuirty stamp is not valid.");
                            UpdateLastLogin = false;
                        }
                        if (user != null)
                        {
                            if (!user.IsActive)
                            {
                                context.Fail("User is not active.");
                                UpdateLastLogin = false;
                            }
                            if (UpdateLastLogin)
                                await userRepository.UpdateLastLoginDateAsync(user, context.HttpContext.RequestAborted);
                        }
                    }
                };
            });
        }
        public static void AddCustomApiVersioning(this IServiceCollection services)
        {
            services.AddApiVersioning(option =>
            {
                #region Option
                //option.AssumeDefaultVersionWhenUnspecified = true;
                //option.DefaultApiVersion = new ApiVersion(1, 0);

                //option.ApiVersionReader = new QueryStringApiVersionReader("api-version");
                // api/posts?api-version=1

                //option.ApiVersionReader = new UrlSegmentApiVersionReader();
                // api/v1/posts

                //option.ApiVersionReader = new HeaderApiVersionReader(new[] { "Api-Version" });
                // header => Api-Version : 1

                //option.ApiVersionReader = new MediaTypeApiVersionReader();
                // Header => Aaccept:application/vnd.mediatype.versioning-v2+json

                //option.ApiVersionReader = ApiVersionReader.Combine(new QueryStringApiVersionReader("api-version"), new UrlSegmentApiVersionReader())
                // combine of [querystring] & [urlsegment]
                #endregion

                option.ReportApiVersions = true;
            });
        }

        public void InstallServices(IServiceCollection services, AppSettings appSettings, IConfiguration configuration,
            IHostEnvironment hostEnvironment)
        {
            services.AddApiVersioning(options =>
            {
                //url segment => {version}
                options.AssumeDefaultVersionWhenUnspecified = false; //default => false;
                options.DefaultApiVersion = new ApiVersion(1, 0); //v1.0 == v1

                options.Conventions.Add(new DefaultODataApiVersion());

                // options.ReportApiVersions = true;

                //options.ApiVersionReader = new QueryStringApiVersionReader("api-version");
                // api/posts?api-version=1

                // options.ApiVersionReader = new UrlSegmentApiVersionReader();
                // api/v1/posts

                //options.ApiVersionReader = new HeaderApiVersionReader(new[] { "Api-Version" });
                // header => Api-Version : 1

                //options.ApiVersionReader = new MediaTypeApiVersionReader()

                //options.ApiVersionReader = ApiVersionReader.Combine(new QueryStringApiVersionReader("api-version"), new UrlSegmentApiVersionReader())
                // combine of [querystring] & [urlsegment]
            });
        }
        public bool Apply(IControllerConventionBuilder controller, ControllerModel controllerModel)
        {
            if (controller.ControllerType.BaseType == typeof(BaseODataController))
            {
                controller.HasApiVersion(1, 0);
                return true;
            }

            return false;
        }


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddApiVersioning(o =>
            {
                o.ReportApiVersions = true;
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
                //这里通过ApiVersionReader属性指定了Api版本号是从请求头部的x-api-version属性来的。
                //o.ApiVersionReader = new HeaderApiVersionReader("x-api-version");
                //在查询字符串中指定版本号的方式将不再可用,如果你希望同时支持2种方式,请改用
                //o.ApiVersionReader = new QueryStringOrHeaderApiVersionReader("x-api-version");  已修改  现版本无此类
                o.ApiVersionReader = ApiVersionReader.Combine( 
                    new QueryStringApiVersionReader("x-api-version"),
                    new HeaderApiVersionReader("x-api-version")
                );
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(c =>
            c.Conventions.Add(
            new ApiExplorerGroupPerVersionConvention()) // decorate Controllers to distinguish SwaggerDoc (v1, v2, etc.)
            );
            services.AddControllers();
            services.AddApiVersioning(options =>
            {
                options.DefaultApiVersion = new ApiVersion(1, 0);
                options.Conventions.Add(new VersionByNamespaceConvention());
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.ReportApiVersions = true;

                //options.ApiVersionSelector = new FallBackApiVersionSelector(options);
                ////header
                options.ApiVersionReader = new HeaderApiVersionReader("api-version");
                //query string
                //options.ApiVersionReader = new QueryStringApiVersionReader("v");
                //route
                //options.ApiVersionReader = new UrlSegmentApiVersionReader();
                //combine
                //options.ApiVersionReader = ApiVersionReader.Combine(
                //    new QueryStringApiVersionReader("v"),
                //    new HeaderApiVersionReader("api-version"));
            });

            //Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "Swagger Document",
                    Description = "A Web API",
                    TermsOfService = new Uri("https://example.com/terms"),

                    License = new OpenApiLicense
                    {
                        Name = "Use under LICX",
                        Url = new Uri("https://example.com/license"),
                    }
                });
                c.OperationFilter<SwaggerParameterAttributeFilter>();
                //c.ResolveConflictingActions(descriptions =>
                //{

                //    var versionDes = descriptions.FirstOrDefault(des => des.GroupName == "v1_0");
                //    return versionDes;
                //});
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // 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(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger V1");
                //c.RoutePrefix = string.Empty;
            });

            //app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
            public void Apply(ControllerModel controller)
            {
                var controllerNamespace = controller.ControllerType.Namespace; // e.g. "Controllers.v1"
                var apiVersion = controllerNamespace?.Split('.').Last().ToLower();
                if (apiVersion != null && apiVersion.Contains("_"))
                {
                    var split = apiVersion.Split('_');
                    apiVersion = split[1] == "0" ? split[0] : apiVersion.Replace('_', '.');
                }

                controller.ApiExplorer.GroupName = apiVersion;
                //controller.ApiExplorer.GroupName = "";
            }

        public static IServiceCollection AddWebFrameworkServices(this IServiceCollection services)
        {
            services.AddApiVersioning(options =>
            {
                //url segment => {version}
                options.AssumeDefaultVersionWhenUnspecified = true; //default => false;
                options.DefaultApiVersion = new ApiVersion(1, 0); //v1.0 == v1
                options.ReportApiVersions = true;

                //ApiVersion.TryParse("1.0", out var version10);
                //ApiVersion.TryParse("1", out var version1);
                //var a = version10 == version1;

                //options.ApiVersionReader = new QueryStringApiVersionReader("api-version");
                // api/posts?api-version=1

                //options.ApiVersionReader = new UrlSegmentApiVersionReader();
                // api/v1/posts

                //options.ApiVersionReader = new HeaderApiVersionReader(new[] { "Api-Version" });
                // header => Api-Version : 1

                //options.ApiVersionReader = new MediaTypeApiVersionReader()

                //options.ApiVersionReader = ApiVersionReader.Combine(new QueryStringApiVersionReader("api-version"), new UrlSegmentApiVersionReader())
                // combine of [querystring] & [urlsegment]
            });

            return services;
        }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
            IHostingEnvironment env,
            IMapper Mapper,
            ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            loggerFactory.AddNLog();
            env.ConfigureNLog("nlog.config");
            app.UseHttpsRedirection();

            app.UseResponseCaching();
            app.UseMvc();
        }

        // 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.EnableEndpointRouting = false;
                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));
            //});
        }

Microsoft.Web.Http.Versioning.ApiVersionReader : Object

Methods :

public static IApiVersionReader Combine(IApiVersionReader[] apiVersionReaders = )
public static IApiVersionReader Combine(IEnumerable<IApiVersionReader> apiVersionReaders = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()