ApiVersionReader

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

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApiVersoning", Version = "V1" });
            });
            services.AddApiVersioning(options=> {
                options.AssumeDefaultVersionWhenUnspecified = true;
                //  options.DefaultApiVersion = new ApiVersion(1, 1); // This will be equalent to version 1.1
                options.DefaultApiVersion = ApiVersion.Default;
                //options.ApiVersionReader = new MediaTypeApiVersionReader("version"); // 1- Passing version info with accept header
                //options.ApiVersionReader = new HeaderApiVersionReader("X-Version"); // 2- Passing version info as Api header

                options.ApiVersionReader = ApiVersionReader.Combine(
                    new MediaTypeApiVersionReader("version"),
                    new HeaderApiVersionReader("X-Version")
                    ); // Combined Passing version info with accept header and Api Header

                //options.Conventions.Controller<UsersController>()
                //.HasDeprecatedApiVersion(1, 0)
                //.HasApiVersion(2, 0)
                //.Action(typeof(UsersController).GetMethod(nameof(UsersController.GetV2))!)
                //.MapToApiVersion(2,0);

                options.ReportApiVersions = true;
            });
        }

        // 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.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApiVersoning v1"));
            }

            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;
            });
        }


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            services.AddApiVersioning(o => {
                o.ReportApiVersions = true;
                //o.ApiVersionReader = new UrlSegmentApiVersionReader();
                o.ApiVersionReader = ApiVersionReader.Combine(new HeaderApiVersionReader("api-version"), new QueryStringApiVersionReader("api-version"));
                //o.ApiVersionReader = ApiVersionReader.Combine(new QueryStringApiVersionReader("api-version"));
                //o.ApiVersionReader = ApiVersionReader.Combine(new HeaderApiVersionReader("api-version"));
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
                o.ApiVersionSelector = new CurrentImplementationApiVersionSelector(o);
            });
        }

        // 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();
            }
            else
            {
                app.UseExceptionHandler("/Home/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();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }


        // 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();
        }

        public static void AddDbContext(this IServiceCollection services, IConfiguration configuration)
        {
            //services.AddDbContext<ApplicationDbContext>(option =>
            //{
            //    option.UseSqlServer(configuration.GetConnectionString("SqlServer"));
            //});
        }

        public static void AddMinimalMvc(this IServiceCollection services)
        {
            //https://github.com/aspnet/Mvc/blob/release/2.2/src/Microsoft.AspNetCore.Mvc/MvcServiceCollectionExtensions.cs
            services.AddMvcCore(options =>
            {
                options.Filters.Add(new AuthorizeFilter());
                options.EnableEndpointRouting = false;
                //Like [ValidateAntiforgeryToken] attribute but dose not validatie for GET and HEAD http method
                //You can ingore validate by using [IgnoreAntiforgeryToken] attribute
                //Use this filter when use cookie
                //options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());

                //options.UseYeKeModelBinder();
            })
            .AddApiExplorer()
            .AddAuthorization()
            .AddRazorPages()
            .AddFormatterMappings()
            .AddDataAnnotations()
            .AddControllersAsServices()
            .AddNewtonsoftJson( /*options =>
            {
                options.Formatting = Newtonsoft.Json.Formatting.Indented;
                options.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            }*/)
            .AddCors(
                options =>
                {
                    options.AddDefaultPolicy(builder =>
                    {
                        builder.WithOrigins(
                            "https://localhost:44366/",
                            "http://localhost:44366/")
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowAnyOrigin();
                    });
                })
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); //.Version_2_1

        }

        public static void AddCustomApiVersioning(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]
            });
        }

        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.AddControllers();
            
            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            
            services.AddScoped<IBlogRepository, BlogRepository>();
            services.AddScoped<ICategoryRepository, CategoryRepository>();

            services.AddAutoMapper();

            services.AddApiVersioning(opt =>
            {
                opt.AssumeDefaultVersionWhenUnspecified = true;
                opt.DefaultApiVersion = new ApiVersion(1,1);
                opt.ReportApiVersions = true;
                
                // TODO:Defining the version through the url
                // opt.ApiVersionReader = new UrlSegmentApiVersionReader();
                
                // TODO:Define the query string name for the api version
                // opt.ApiVersionReader = new QueryStringApiVersionReader("ver");
                
                // TODO:Define the header name for the api version
                // opt.ApiVersionReader = new HeaderApiVersionReader("X-Version");
                
                // TODO:Defining multiple ways for the api version
                // opt.ApiVersionReader = ApiVersionReader.Combine(
                // new HeaderApiVersionReader("X-Version"),
                // new QueryStringApiVersionReader("ver", "version"));
            });
            
            services.AddMvc(opt => opt.EnableEndpointRouting = false)
                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            services.AddControllers().AddNewtonsoftJson(options =>
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
        }

        // 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(); });
        }

Microsoft.AspNetCore.Mvc.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()