1

A .net framework library contains the following method :

public static void SetSqlLogOn(bool TrueOnFalseOff)
    {
        HttpContext.Current.Session["LM_SQLLOG"] = TrueOnFalseOff;
    }

We are now converting it to net core. We tried Microsoft.AspNetCore.Http which doesn't work the way the above method does.What is the way to write this method in net core?

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Saiful Islam
  • 139
  • 5
  • 16
  • Have you looked up session state in .Net Core? https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2#session-state – David Mar 14 '19 at 09:19
  • https://visualstudiomagazine.com/articles/2018/12/01/working-with-session.aspx "... you can't reasonably expect to migrate your ASP.NET MVC application to ASP.NET MVC Core". – Ian Kemp Mar 14 '19 at 09:24
  • Yes.I tried with the Microsoft.AspNetCore.Session package.It doesn't seem to be applicable to libraries but web applications. – Saiful Islam Mar 14 '19 at 09:28
  • @IanKemp I can't migrate a library from framework to core? – Saiful Islam Mar 14 '19 at 09:31
  • 1
    @SaifulIslam The `System.Web.HttpContext` class does not exist in .NET Core, its replacement is `Microsoft.AspNetCore.Http.IHttpContextAccessor` which exposes an `HttpContext` property, but has to be injected. https://stackoverflow.com/questions/31243068/access-the-current-httpcontext-in-asp-net-core – Ian Kemp Mar 14 '19 at 10:34
  • @IanKemp I have used IHttpContextAccessor. But there's no method for setting a boolean value.Is there a way around? – Saiful Islam Mar 14 '19 at 11:12
  • 1
    @SaifulIslam No, because the `Microsoft.AspNetCore.Http.ISession` interface does not expose a method to do so, nor does it expose an indexer like `System.Web.SessionState.HttpSessionState`. `Microsoft.AspNetCore.Http.ISession` 's methods for getting/setting also only support `byte` arrays and not plain `object`s, but there are extension methods to use strings, so you can probably just call `ToString()` on your value and save that. – Ian Kemp Mar 14 '19 at 12:56

1 Answers1

0

What you need is the IHttpContextAccessor, it gives you the properties you are after in the context of the current call.

It needs to be injected using the built in dependency injection framework. The easiest example is to add the IhttpContextAccessor as a constructor parameter to one of your controllers, and stick a breakpoint on it - register the accessor in the ServicesCollection using the extension method and run your application. You'll be able to see it in action.

A more detailed write-up with example can be found here: https://adamstorr.azurewebsites.net/blog/are-you-registering-ihttpcontextaccessor-correctly

Robert Perry
  • 1,906
  • 1
  • 14
  • 14