简体   繁体   中英

how to solve this error when upgrade from core 2.1 to core 3.1 OptionsValidationException: Cookie.Expiration is ignored, use ExpireTimeSpan instead

I have upgraded my asp.net core 2.1 application to asp.net core 3.1, but when I run the project I got this error OptionsValidationException: Cookie. Expiration is ignored, use ExpireTimeSpan instead. OptionsValidationException: Cookie. Expiration is ignored, use ExpireTimeSpan instead. the first display of my application show this error

here is my startup code asp.net core 3.1, that I have upgraded from .net core 2.1,

  public class Startup
{
    public IConfiguration Configuration { get; }
    public IWebHostEnvironment Environment { get; }
    public Startup(IConfiguration configuration, IWebHostEnvironment environment)
    {
        Configuration = configuration;
        Environment = environment;
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        var connection = Configuration.GetConnectionString("DentalDBconnection");
        services.AddDbContext<HoshmandDBContext>(option => option.UseSqlServer(connection));
        services.AddAuthentication(option =>
        {
            option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            option.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            option.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie(options =>
        {
            options.LoginPath = "/Logins/UserLogin/";
            options.AccessDeniedPath = "/AccessDenied";
            options.Cookie.Expiration = new TimeSpan(10, 00, 00);
        });

        services.AddDistributedMemoryCache();
        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromHours(2);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;

        });

        services.ConfigureApplicationCookie(option =>
        {
            option.ExpireTimeSpan = TimeSpan.FromMinutes(540);
        });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("HasAccess", policy => policy.AddRequirements(new HasAccessRequirment()));
        });
        // services.AddTransient<IFingerPrint, FingerPrint>();
        services.AddTransient<IAuthorizationHandler, HasAccessHandler>();
        services.AddTransient<IMvcControllerDiscovery, MvcControllerDiscovery>();
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app)
    {
        if (Environment.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        var cachePeriod = Environment.IsDevelopment() ? "600" : "604800";
        app.UseStaticFiles(new StaticFileOptions
        {
            OnPrepareResponse = ctx =>
            {
                ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}");
            }
        });
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseCors();
        app.UseAuthentication();
        app.UseCookiePolicy();
        app.UseSession();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(name: "default", pattern: "{controller=UserProfiles}/{action=Index}/{id?}");
        });

please help me, what else I need to change when upgrating from asp.net core 2.1 to asp.net core 3.1 to not got this error Thank you

New Section Code Added

I think the issue is somewhere else by default in my startup code user redirects to this controller, from EndPoint

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

in UserProfile Controller there is, a check if a user is not login, this function redirects to the user's login page

public async Task<IActionResult> Index(bool? passIsChanged = null) // userId
    {
        if (passIsChanged != null)
        {
            ViewBag.isSuccessed = passIsChanged;
        }
        int id = Convert.ToInt32(User.Identity.Name);
        var user = _context.UserAccountTbs.FirstOrDefault(a => a.UserId == id);
        if (user == null)
        {
            return RedirectToAction("UserLogin", "Logins");
        }

From UserProfile when GO to the login page this Error Happens

Use options.ExpireTimeSpan instead of options.Cookie.Expiration (which, yes, is ignored).

services.AddAuthentication(...)
   .AddCookie(options =>
   {
       options.LoginPath = "/Logins/UserLogin/";
       options.AccessDeniedPath = "/AccessDenied";
       options.ExpireTimeSpan = new TimeSpan(10, 00, 00);
   });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM