在类库中使用HttpCookieCollection的asp.net core 2.2

时间:2018-12-24 17:55:27

标签: c# .net asp.net-core .net-core asp.net-core-mvc

我正在从旧的.net“升级”到.net core 2.2(显然,这不是容易升级,因为它是可重写的)

  

HttpCookieCollection不再可用。对于.Net Core 2.2类库,如何访问此Cookie集合的示例有哪些?

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

2 个答案:

答案 0 :(得分:2)

我相信等效的课程将是IRequestCookieCollection

可以通过控制器中的if (num > even){ even = num; count = 1; } else { count++; } 在请求实例中访问此对象的实例。

答案 1 :(得分:-1)

您可以使用HttpContext访问Cookies

为此,您需要注入IHttpContextAccessor。用法是:

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

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

如果您在控制器中,则可以直接使用HttpContext.Request.Cookies["someCookie"]

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

        return View();
    }
}