2

HttpContext.Session.GetInt32 ("Id") throws null exception because session doesn't occur when my c# code is running first on my layaut page

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

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

ActionResult

.....

            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 and UserSrgu -> full and id = null and usr = null

I passed layout.cshtml page by passing data with TempData

3
  • have you set httpcontect in startup.cs HttpContext.Session is available after session state is configured. Commented Dec 19, 2019 at 21:28
  • 1
    please convert your question into english Commented Dec 19, 2019 at 21:40
  • Can't I read null value with HttpContext.Session.GetInt32 ("Id") without assigning session id si.,? Commented Dec 19, 2019 at 22:50

1 Answer 1

2

1-In the ConfigureServices method please make sure you have set CheckConsentNeeded to false.

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

2- A call to AddSession in ConfigureServices.

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- in Configure method in startup.cs you should have :

  app.UseSession();
Sign up to request clarification or add additional context in comments.

4 Comments

both available her ikiside mevcut
@ErolAKTEPE i don't see it on your code , please check above three essentials again.
options.Cookie.IsEssential = true; unsolved problem in progress
@ErolAKTEPE may you please share SessionExtensions class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.