为什么我不能使用 HttpContext 或 HttpCookie?(ASP.NET 核心 1.0)

Yan*_*nik 5 c# asp.net cookies asp.net-mvc asp.net-mvc-5

为什么我不能使用HttpContextHttpCookie?有什么特殊用途吗?

我的实际用途:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
Run Code Online (Sandbox Code Playgroud)

我的命名空间:

namespace eCoffee.Main
Run Code Online (Sandbox Code Playgroud)

我的课程+方法:

public class AppRunCookie
{
    public static string CookieName { get; set; }
    public static string Key { get; set; }
public AppRunCookie(string key)
{
    CookieName = "MyCookie_" + key;
}

public static void SetCookie(string key, int cookieExpireDate = 30)
{
    HttpCookie myCookie = new HttpCookie(CookieName);
    myCookie["Key"] = key;
    myCookie.Expires = DateTime.Now.AddDays(cookieExpireDate);
    HttpContext.Current.Response.Cookies.Add(myCookie);
}

public string GetCookie()
{
    HttpCookie myCookie = HttpContext.Current.Request.Cookies[CookieName];
    if (myCookie != null)
    {
        string key = Convert.ToString(myCookie.Values["Key"]);
        return key;
    }
    return "";
}
}
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Yan*_*nik -2

大家好

\n\n

我找到了一个解决方案,尝试使用这个精彩的博客条目。

\n\n

注意: \n确保通过 nuget 安装程序安装 nuget 软件包,并确保选中复选框 \xe2\x80\x9cinclude prerelease\xe2\x80\x9d。

\n\n

希望我的帖子有帮助

\n

  • 那篇文章是为了实现Session。但如果你想实现 cookie 处理,我建议使用 Microsoft.AspNetCore.Http 命名空间和以下类 Microsoft.AspNetCore.Http.HttpResponse、Microsoft.AspNetCore.Http.HttpRequest 和 Microsoft.AspNetCore.Http.CookieOptions (3认同)