繁体   English   中英

会话无法正常工作,并在视图中返回Null

[英]Session not working and returning Null in the view

我不知道在哪里寻找; 我是asp.net核心的新手,会话对象一直工作到今天。

这是我的创业班

public Startup(IHostingEnvironment hostingEnvironment, IConfiguration configuration, ILoggerFactory loggerFactory)
    {
        Configuration = configuration;
        this.extensionsPath = hostingEnvironment.ContentRootPath + this.Configuration["Extensions:Path"];
        this._hostingEnvironment = hostingEnvironment;
    }

    public IConfiguration Configuration { get; }
    public IHostingEnvironment _hostingEnvironment;

    private string extensionsPath;

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<RazorViewEngineOptions>(options => {
            options.ViewLocationExpanders.Add(new ViewLocationExpander(_hostingEnvironment));
        });



        services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContext‌​Accessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

        services.AddTransient<IBusinessServiceLocator, BusinessServiceLocator>();
        services.AddTransient<IBusinessApiCalls, BusinessApiCalls>();

        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddTransient<IUserService, UserService>();

        services.AddAuthorization(o =>
        {

            o.AddPolicy("policyforcontrollers", b =>
            {
                b.RequireAuthenticatedUser();
            });
        });

        services.RegisterDataTables();
        services.AddMemoryCache();
        services.AddSession(opt =>
        {
            opt.Cookie.IsEssential = true;
        });

        services.AddAuthentication(options =>
        {

            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
           .AddCookie(options =>
           {
               options.LoginPath = "/usr/login";
               options.LogoutPath = "/usr/logout";
           });

        services.AddExtCore(this.extensionsPath);
        services.AddMvc(options =>
        {
            options.Conventions.Add(new AuthorizeControllerModelConvention());
        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }


    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseSession();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
               name: "areas",
               template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
             );

            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
        app.UseExtCore();
    }

这是我的会议助手

public static class SessionExtensions
{
    public static void SetJson(this ISession session, string key, object value)
    {
        session.SetString(key, JsonConvert.SerializeObject(value));
    }

    public static T GetJson<T>(this ISession session, string key)
    {
        var sessionData = session.GetString(key);
        return sessionData == null ? default(T) : JsonConvert.DeserializeObject<T>(sessionData);
    }
}

public  class SessionObject
{
    public static string User { get; } = "USER";
}

从用户控制器,我设置会话

    await LoginAsync(user);
    HttpContext.Session.SetJson(SessionObject.User, user);

从视图我访问会话对象为

 @{
     ViewBag.Title = "Home";
     Layout = "_Layout";
     var session = Context.Session.GetJson<LoggedInUser>(SessionObject.User);

 }

视图中的会话对象为Null我注意到,来自用户控制器的会话ID和视图中的会话对象ID是不同的。 我找不到它不再起作用的原因。 我想念什么?

在CookieCookiePolicyOptions中,将CheclConsentNeeded设置为false。

services.Configure<CookiePolicyOptions>(options =>
{
  options.CheckConsentNeeded = context => false;
  options.MinimumSameSitePolicy = SameSiteMode.None;
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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