简体   繁体   中英

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);
}

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.

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM