how to resolve the type or namespace "HttpContextBase " could not be found in ASP.Net class library in a new class library i created

2020-05-27 asp.net asp.net-mvc

public class BasketService { IRepositoryBase baskets;

    public const string BasketSession = "eCommerceBasket";
    public BasketService(IRepositoryBase<Basket> baskets)
    {
        this.baskets = baskets;
    }
    private Basket CreateNewBasket(HttpContextBase httpContext)
    {

    }
}

Answers

If this is really what you want...

The HttpContextBase class is in the System.Web namespace. So you'll either need to fully-qualify the class name:

private Basket CreateNewBasket(System.Web.HttpContextBase httpContext)
{

}

or add the appropriate using directive at the top of your code file:

using System.Web;

If you then get an error that HttpContextBase isn't in that namespace or that the namespace doesn't exist, double-check that you've added the reference to your project. In the Solution Explorer in Visual Studio, right-click on the "References" node in the project and select "Add Reference". Navigate to the "Assemblies" to find and select System.Web. Click "OK".


Having said that... Are you sure this is the design you want? If your goal is to make a generic service which can be used by different applications, making that service depend on the web application would be ill-advised. What happens if you want to use it in a Console Application? There's no web context there.

Instead of making your general-purpose code depend on UI-specific things, turn that around. Make your UI-specific applications depend on the general-purpose code. So for this particular method, ask yourself...

What would I need to "create" a new "basket"?

Whatever information that is, that's what CreateNewBasket should accept as parameters. Maybe it's a handful of values, maybe it's a custom object, that's up to you. But "creating a basket" does not require an HTTP context. It requires some values that you are expecting to find in your HTTP context at a particular time.

The application layer should be responsible for pulling those values from the HTTP context and providing them to CreateNewBasket. The general-purpose code should just require the values themselves.

Related