9

I am trying to access session data from inside a view.

Use Case: I'm storing status messages in the session that will be displayed at the top of the page. Currently I implemented this by using a DisplayMessages() function that sets some ViewData[....] properties and calling it at the beginning of every controller action.

Goal: I want to only set the status message once without needing additional code in the controller to display the messages on the next page load.

So I'm trying to access the messages that are stored in the session directly from the view.

So far I have tried the following:

  • Dependency Injection of an IHttpContextAccessor (doesn't seem to work anymore with ASP .NET Core MVC 1.0.0
  • Creating a static class to access the session, including the change from next() to next.invoke() suggested in the comment
    • This didn't work. I could access the HttpContext and Session.IsAvailable was true, but there was no data in the session.
FSMaxB
  • 2,280
  • 3
  • 22
  • 41

2 Answers2

20

The following should work in the view: Context.Session.TryGetValue

If you are using the SessionExtensions then Context.Session.GetString will work.

bvoleti
  • 2,472
  • 1
  • 18
  • 20
  • 3
    Accessing it via 'Context' instead of 'HttpContext' worked. – FSMaxB Aug 31 '16 at 06:16
  • 4
    @FSMaxB If you add `@using Microsoft.AspNetCore.Http;` in your view, you can use Context.Session.GetString("") – adem caglin Aug 31 '16 at 06:19
  • @ademcaglin Yes, I already loaded the extensions. Thanks anyway. – FSMaxB Aug 31 '16 at 07:21
  • The GetString() method works well, but for me... it adds quotes around the retrieved value. Why on earth does it have to do that? That's completely unnecessary. If I wanted quotes around my strings, I'd do it myself. – Jay Dec 10 '18 at 18:16
1

Injecting IHttpContextAccessor does work, but starting with ASP.NET Core 1.0.0 RC2, the IHttpContextAcessor is not registered by default, because it has significant performance overhead per request. See this GitHub announcement for more information.

Tratcher posted:

IHttpContextAccessor can be used to access the HttpContext for the current thread. However, maintaining this state has non-trivial performance costs so it has been removed from the default set of services.

Developers that depend on it can add it back as needed: services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

But in your use case, I would suggest using a ViewComponent, which is a reusable piece of View with logic, that do not depend on a controller.

The documentation can be found here.

In your Views you would simply embed it with

@await Component.InvokeAsync("PriorityList", new { maxPriority = 2, isDone = false })

or

@Component.Invoke("PriorityList", new { maxPriority = 2, isDone = false })

for synchronous calls.

Community
  • 1
  • 1
Tseng
  • 61,549
  • 15
  • 193
  • 205