简体   繁体   中英

ASP 5 MVC 6 beta8, get Session using razor (better way)

I write that code to retrieve session values

  @{
    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>
    }
}

Is there any better way to retrieve values( using less lines etc)

A possible simplification:

At the top of your cshtml add

@using Microsoft.AspNet.Http;

This gives access to the GetString method

Context.Session.GetString("test");

I'd imagine your code simplified can then look like

@{
    string sessionName = Context.Session.GetString("name");
    if (sessionName != null)
    {
        <p>@sessionName</p>
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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