I'm trying to migrate an ASP.NET MVC site to ASP.NET Core with the .NET Core runtime. Previously we could get objects out of the session store, even in different assemblies, with
var obj = HttpContext.Current.Session[key]
Now I've read we must inject IHttpContextAccessor and use the method on _contextAccessor.HttpContext.Session. But the methods of the Session object have changed, and it no longer has indexing applied.
I have seen people in other questions using HttpContext.Session.GetString() and HttpContext.Session.SetString():
Access HttpContext.Current
With these I could at least de/serialize the object I want to fetch/get. But I can't find these methods on the interface.
'ISession' does not contain a definition for 'GetString' and no extension method 'GetString' accepting a first argument of type 'ISession' could be found
How to I get access to these methods?
HttpContext is just the current HttpContext exposed to you by the Controller class. If you’re not in a controller, you can still access the HttpContext by injecting IHttpContextAccessor. Let’s go ahead and add sessions to our Home Controller: You’ll see the Index () and About () methods making use of the Session object.
However, there was a problem. For every single component where we need to access the session, we have to inject a dependency of IHttpContextAccessor. While it's not a problem for one or two components, it can be very daunting if we have to do the same over and over again.
If you’re not in a controller, you can still access the HttpContext by injecting IHttpContextAccessor. Let’s go ahead and add sessions to our Home Controller:
To enable that, you need to add HttpContextAccessor in your service collection in ConfigureServices method in Startup.cs
GetString
is an extension method in the Microsoft.AspNetCore.Http.Extensions
assembly, make sure you have a reference to that. You may also need to import it:
using Microsoft.AspNetCore.Http;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With