Accessing httpcontext in class library with ASP.NET Core 1.1 (MVC)
Asked Answered
C

4

7

I am working on migrating my ASP.NET 4.6 framework code over to .NET Core. I'm only in the learning phase at this point. I'm new to MVC as I've always used WebForms, but I want to move away from WebForms. I'm also new to ASP.NET Core.

Basically, I have a class library that does the bulk of my work - saving me from repeating code (database, session, custom identity management) across multiple pages or even websites. I add the DLL to a project, and it's ready to go.

I'm finding that ASPNET Core doesn't quite allow this. Perhaps I'm not understanding it, or perhaps it's too early to start porting over to it.

I need to be able to access HttpContext inside my class library to manipulate things like sessions, cookies, etc. What is the easiest way to approach this? I think once I can do that, I can start making better progress.

Or, do I need to reconsider writing a class library? From my understanding, I need to write Middleware to accomplish this. But every example I could find is either incomplete or outdated already.

Any suggestions are welcome.

Cotidal answered 20/4, 2017 at 19:24 Comment(4)
The answer you have already is correct, but from reading your post maybe you could post some example code of what you have already (A simple class with just one method showing), and then people could help you specifically with your issues (It may well fit better into middleware for example).Pro
Thank you - I actually have only been writing test code, so there's no code to really put out. However, I did figure it out based on this article: blog.planetdiego.com/2016/10/…Cotidal
I devised a way that you can use: https://mcmap.net/q/660825/-how-to-use-sessions-in-a-net-core-2-0-class-library-projectAnthurium
I devised a way that you can use #48371804Anthurium
M
17

Using HttpContext for all-around logic is not a great idea but if you really intend to do so, just stick to one of SOLID principles, ie. Dependency inversion principle.

ASP.NET MVC and it successor, ASP.NET Core have their foundations laid on this very principle. Inject IHttpContextAccessor in constructor of any class from your class library that needs it.


Example:

public class ContextHelper
{
    private IHttpContextAccessor _httpContextAccessor;

    public ContextHelper(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void DoStuff()
    {
        DoOtherStuffWith(_httpContextAccessor.HttpContext);
    }
}

Remember to register it in Startup in default IoC container like this:

public class Startup
{
    // Rest of the class here...

    public void ConfigureServices(IServiceCollection services)
    {
        // Other registrations here...

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }
}
Message answered 20/4, 2017 at 19:36 Comment(1)
Thank you!! I finally figured out what I needed and it works swell! Here is the article I found: blog.planetdiego.com/2016/10/… Looks like my Friday night is going to be a night of learning (yay).Cotidal
S
5

Step1: In Startup Class -> in ConfigureServices Add the below line

services.AddHttpContextAccessor();

Step2:In your class library. Eg.

public class Dog
    {
        public HttpContext _httpContext => new HttpContextAccessor().HttpContext;
        public void Speak()
        {
            _httpContext.Response.WriteAsync("Dog says: Bow-Wow...\n");
        }
    }
Scherzando answered 13/5, 2021 at 17:22 Comment(1)
That saved me lot of timeChlorpromazine
G
2

In asp.netcore mvc the HttpContext is made inaccessible outside the scope of controller. So, there is no way you can access HttpContext in your class library directly. You have to access it in some other ways.

You can send the HttpContext to your class library either from the constructor of your Controller to the constructor of your class library class or to the specific library method that needs the current HttpContext from the action method of the controller.

Guardianship answered 21/4, 2017 at 6:35 Comment(2)
Thank you. What do you think of this method? blog.planetdiego.com/2016/10/…Cotidal
Yes. This is another way to go :)Guardianship
A
1

There are two ways to access the HTTPContext in the class library.

  1. Constructor
  2. Create a instance for the static class scenario

It can be achieved via the dependency injection which injects the httpcontext to the class. I've worked out the code samples for both the scenario that you can refer here

Asparagus answered 2/9, 2023 at 8:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.