7

In ASP.NET 5 MVC 6 Beta 8 I need to read a session variable in in my _Layout.cshtml or alternatively get a reference to the current HttpContext.

Take note: In ASP.NET 5 referencing the Session object has changed significantly from ASP.net 4 as detailed in this question

The Context object has also been renamed to HttpContext between Beta7 and Beta8.

In My current controller I currently save the session variable like this

public IActionResult Index()
{
    HttpContext.Session.SetInt32("Template", (id));
}

In my _Layout.cshtml I need to read the above session variable. I need to reference the current HttpContext somehow e.g

HttpContext.Current.Session.GetInt32("Template");

but I don't know how to the get the current HttpContext in a cshtml file.

2 Answers 2

17

The naming between Context and HttpContext is somewhat confusing. You can access the HttpContext in a view using the Context property:

@{ int x = Context.Session.GetInt32("test"); }

There is also a pending issue at the MVC repo regarding this: https://github.com/aspnet/Mvc/issues/3332

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the correct answer and GitHub link. What caught me out was that in the controller it is called HttpContext but in the View it is only Context.
Yeah, in beta8 they renamed it to HttpContext in the controller but they 'forgot' about the view.
6

using razor, you can get values this way

@{
var sessionName = new Byte[20];
bool nameOK = Context.Session.TryGetValue("name", out sessionName);

if (nameOK)
{
    string result = System.Text.Encoding.UTF8.GetString(sessionName);
    <p> @result</p>

}
}

change

string result = System.Text.Encoding.UTF8.GetString(sessionName);

to

int intSessionValue = Int32.Parse(sessionName);

or to be safer

int intSessionValue = 0;
bool isConvertOK = Int32.TryParse(TextBoxD1.Text, out intSessionValue);

So you can check if conversion was successful

if (isConvertOK){
   //successful conversion from string to int
}

Comments

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.