pavan
pavan

Reputation: 34

Accessing session variable in Razor Layout?

When i write code in my layout page

Profile

@Session["iname"].ToString();

I got this error

Object reference not set to an instance of an object.

i tried @HttpContext.Current.Session["iname"].ToString() but not working

Upvotes: 1

Views: 9329

Answers (2)

William Naranjo
William Naranjo

Reputation: 71

you can do this in the design

@using Microsoft.AspNetCore.Http
@if (Context.Session.GetString("iname") != null){}

Upvotes: 6

James
James

Reputation: 2201

This means that there is nothing with the key "iname" in Session. Null check this before you use ToString:

@if(Session["iname"] != null)
{
    Session["iname"].ToString();
}

Upvotes: 4

Related Questions