【问题标题】:Why I can't use HttpContext or HttpCookie? (Asp.Net Core 1.0)为什么我不能使用 HttpContext 或 HttpCookie? (Asp.Net Core 1.0)
【发布时间】:2016-11-15 17:25:06
【问题描述】:

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

我的实际用途:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

我的命名空间:

namespace eCoffee.Main

我的班级+方法:

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

我做错了什么?

【问题讨论】:

  • “不能使用”到底是什么意思?你的错误信息是什么?如果您使用的是 Visual Studio,您可以让 VS 创建缺少的 using 语句,方法是选择有错误的行,然后按 ctrl+。并选择适当的选项。
  • @TimPohlmann 我找到了一些关于 stackoverflow 的教程。在本教程中,他们使用了 HttpCookie 语句。我试图在我自己的项目中实现这一点。 VB2015 告诉我:“找不到类型或命名空间 HttpCookie....”你是对的 VB 在正常情况下会给出一些“to do”,但在这种情况下 VB 不会给出“to do” HttpContext 方法可以我已经使用了,因为我遵循 VB 的“to do”。这是因为我使用的是最新的 .NET Core 吗?
  • VB?我假设您的意思是 VS(又名 Visual Studio)。奇怪的是它没有提出用途。
  • @TimPohlmann 对不起我的错误:我的意思是 VS for Visual Studio :)
  • 如果您使用的是 ASP.Net MVC,请注意 HttpContext 位于 Controller 部分下,因为使用该框架更改了页面生命周期。 msdn.microsoft.com/en-us/library/… 可能对更多细节有用。

标签: c# asp.net asp.net-mvc cookies asp.net-mvc-5


【解决方案1】:

HttpContextHttpCookie 的命名空间是 System.Web,它是 System.Web.dll 库的一部分。

右击项目References 并选择Add References...。在新打开的窗口中点击Assemblies,然后搜索(通过右上角的搜索栏)System.Web

那么你应该可以通过

using System.Web;

【讨论】:

  • 根据@JB King 对 OP 的评论,HttpContext 将在控制器的范围内。因此,尽管using System.Web 将允许您访问HttpContext 对象,但它与应用程序的其余部分不在同一范围内 - 因为HttpContext 在控制器范围内
  • @GeoffJames 看我的评论
  • @Yannikhere 我不知道您为什么缺少该程序集,抱歉。
  • @TimPohlmann ;( 我创建了一个普通的 ASP.NET Core Web 应用程序大声笑。如果它对你有用,你能打开我的项目试试吗?请 [github](github.com/YannikG/eCoffee/tree/master/eCoffee) IIf 你完成了我请反馈...我将提交最新版本等待...
  • @Yannikhere 我的猜测是,它与作为 ASP.NET Core Web 应用程序的项目有关。我不熟悉那些。在一个常规的 C# 项目中,我的解决方案工作得很好。
【解决方案2】:

大家好

我找到了解决办法,尝试使用this精彩博文。

注意: 确保通过 nuget 安装程序安装 nuget-packages,并确保选中“包含预发布”复选框。

希望我的帖子对你有帮助

【讨论】:

  • 那篇文章是用来实现Session的。但如果你想实现 cookie 处理,我建议使用 Microsoft.AspNetCore.Http 命名空间和以下类 Microsoft.AspNetCore.Http.HttpResponse、Microsoft.AspNetCore.Http.HttpRequest 和 Microsoft.AspNetCore.Http.CookieOptions
猜你喜欢
  • 2021-05-05
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 2020-09-22
  • 2018-07-24
  • 1970-01-01
  • 1970-01-01
  • 2019-04-18
相关资源
最近更新 更多