user10189172
user10189172

Reputation:

asp.net core 2.2 using HttpCookieCollection in a class library

I am "upgrading" from old .net to .net core 2.2 (obviously it's not such as easy upgrade as it is a re-write)

This HttpCookieCollection is not so accessible anymore. For .Net Core 2.2 class library what are some examples of how to get access to this cookie collection?

private static string CollectionToHtmlTable(HttpCookieCollection collection)
{
    // Converts HttpCookieCollection to NameValueCollection
    var nvc = new NameValueCollection();
    foreach (string item in collection)
    {
        var httpCookie = collection[item];
        if (httpCookie != null)
        {
            nvc.Add(item, httpCookie.Value);
        }
    }

    return CollectionToHtmlTable(nvc);
}

Upvotes: 4

Views: 3715

Answers (2)

Dan
Dan

Reputation: 883

I believe the equivalent class would be IRequestCookieCollection

An instance of this object can be accessed in the request instance via HttpContext.Request.Cookies in a controller.

Upvotes: 5

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30625

You can access Cookies using HttpContext

For this you would want to inject IHttpContextAccessor. the usage is:

public class MyClass
{
    private readonly IHttpContextAccessor _contextAccessor;
    public MyClass (IHttpContextAccessor contextAccessor)
    { 
         _contextAccessor = contextAccessor;
    }

    public void MyFunction()
    {
         var someCookie = _contextAccessor.HttpContext.Request.Cookies["someCookie"];
    }
}

If you are in the controller, you can directly use HttpContext.Request.Cookies["someCookie"]

public class HomeController : Controller
{
    public IActionResult About()
    {
        var someCookie = HttpContext.Request.Cookies["someCookie"];

        return View();
    }
}

Upvotes: 0

Related Questions