Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IHttpContextAccessor Session GetString

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?

like image 520
zola25 Avatar asked Jun 30 '17 16:06

zola25


People also ask

How do I add httpcontext to a session?

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.

Is there a problem with ihttpcontextaccessor?

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.

How do I access httpcontext If I’m not in a controller?

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:

How to enable httpcontextaccessor in service collection?

To enable that, you need to add HttpContextAccessor in your service collection in ConfigureServices method in Startup.cs


1 Answers

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;
like image 83
DavidG Avatar answered Sep 21 '22 06:09

DavidG