c# - ASP.NET CORE 3.1 读取 session 时未分配初始值时出现 NULL 异常错误

标签 c# asp.net-mvc asp.net-core

HttpContext.Session.GetInt32 ("Id") 抛出 null 异常,因为当我的 C# 代码首先在我的布局页面上运行时, session 不会发生

Session ilk okunduğunda sanırım henüz oluşturulmamış olduğu için null exception fırlatıyor. hatta login sayfasında session girildikten sonra bile layout sayfasında okurken null exception fırlatıyor.

 public ActionResult Login(string sifre, string email)
        {
            var url = HttpContext.Session.GetString("url");

            User UserSrgu = (from p in db.User
                             where p.Email == email && p.Sifre == sifre
                             select p).SingleOrDefault();
            if (UserSrgu == null)
            {
                TempData["sayfaMsj"] = "Lütfen E-mail ve Şifrenizi doğru giriniz!!!";
                return View();
            }
            if (UserSrgu.Onaylimi)
            {
                if (UserSrgu.ResimYol == null || UserSrgu.ResimYol == "")
                {
                    UserSrgu.ResimYol = "/Content/nullimgs/no-image_ex.png";
                }


                **HttpContext.Session.SetInt32("Id", UserSrgu.Id);
                HttpContext.Session.SetString("KAdi", UserSrgu.KAdi);
                HttpContext.Session.SetString("AdSoyad", UserSrgu.AdSoyad);
                HttpContext.Session.SetString("Email", UserSrgu.Email);
                HttpContext.Session.SetString("ResimYol", UserSrgu.ResimYol);**




                if (url != null)
                {
                    url = HttpContext.Session.GetString("url");
                }
                else
                {
                    url = "login";
                }
                return Redirect(url.ToString());
            }
            else
            {
                TempData["sayfaMsj"] = "Lütfen E-mail adresinize gelen linkten doğrulma yapınız!!!";
                return View();
            }
        }

layaout.cshtml页面

@page
@using Microsoft.AspNetCore.Http
@using System.Text
@{

    var contentKAdi = "";
    var contentAdSoyad = "";
    var contentEmail = "";
    var contentResimYol = "";
    int contentId = 0;

    try
    {
        ***usr = HttpContext.Session.Get<User>("user");
        contentId = (int)HttpContext.Session.GetInt32("Id"); 
        contentKAdi = HttpContext.Session.GetString("KAdi");***
    }
    catch
    {
        contentKAdi = "";
        contentAdSoyad = "";
        contentEmail = "";
        contentResimYol = "";
        contentId = 0;
    }


}

startap.cs

    public void ConfigureServices(IServiceCollection services)
    {
        var connection = Configuration.GetConnectionString("xxZZDatabase");
        services.AddDbContext<xxZZContext>(option => option.UseSqlServer(connection));
        services.AddHttpClient();
        services.AddControllersWithViews();
        services.AddHttpContextAccessor();
        services.AddDistributedMemoryCache();
        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(10);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
            options.Cookie.Name = ".Erol.Aktepe";
        });

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

        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddDistributedRedisCache(options =>
        {
            options.InstanceName = "Oturum";
            options.Configuration = "127.0.0.1";
        });



        services.AddMvc(options => options.EnableEndpointRouting = false) 
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

    }



    [Obsolete]
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {

        app.UseSession();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();           
        }
        else
        {
            app.UseExceptionHandler("/Error");            
        }


        app.UseStaticFiles();


        app.UseRouting();

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

    }

SessionExtensions.cs

public static class SessionExtensions
{
    public static byte[] Get(this ISession session, string key);
    public static int? GetInt32(this ISession session, string key);
    public static string GetString(this ISession session, string key);
    public static void SetInt32(this ISession session, string key, int value);
    public static void SetString(this ISession session, string key, string value);
}

Action 结果

...

            if (HttpContext.Session.Get<User>("user") == default(User))
            {
                HttpContext.Session.Set<User>("user", UserSrgu);
                var usr = HttpContext.Session.Get<User>("user");
            }
            HttpContext.Session.SetInt32("Id", UserSrgu.Id);
            var id = HttpContext.Session.GetInt32("Id");

...... UserSrgu.Id = 1 且 UserSrgu -> full 且 id = null 且 usr = null

我通过使用TempData传递数据来传递layout.cshtml页面

最佳答案

1-在 ConfigureServices 方法中,请确保您已将 CheckConsentNeeded 设置为 false。

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

2- 在 ConfigureServices 中调用 AddSession

public void ConfigureServices(IServiceCollection services)
{
    services.AddDistributedMemoryCache();

    services.AddSession(options =>
    {
        // Set a short timeout for easy testing.
        options.IdleTimeout = TimeSpan.FromSeconds(10);
        options.Cookie.HttpOnly = true;
        // Make the session cookie essential
        options.Cookie.IsEssential = true;
    });

3-在 startup.csConfigure 方法中,您应该具有:

  app.UseSession();

关于c# - ASP.NET CORE 3.1 读取 session 时未分配初始值时出现 NULL 异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59417013/

相关文章:

asp.net - 当前模型不再匹配用于预生成映射 View 的模型

c# - 强制 ASP.NET Core Entity Framework Core 中的继承类到专用 MySQL 表

c# - MVC3 动态 ListView

c# - C# travis 的问题

asp.net-mvc - PerRequestLifetimeManager 和 Task.Factory.StartNew - 使用 Unity 进行依赖注入(inject)

c# - AuthenticationManager.SignIn() 不存在于 AuthenticationManager 类中

c# - 如果 Finalizer 调用 Dispose() ,您可以触发 "Disposing"事件吗?

c# - 当文件名中不存在文件扩展名时从文件中检索文件扩展名(在 C# 中)?

visual-studio - Docker Desktop for Windows + ASP.NET Core 错误

c# - 找不到类型或命名空间名称 'DefaultHttpRequest'