【问题标题】:HttpContextBase namespace could not be found找不到 HttpContextBase 命名空间
【发布时间】:2017-06-27 08:20:00
【问题描述】:
public string GetCartId(HttpContextBase context)
{
    if (context.Session[CartSessionKey] == null)
    {
        if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
        {
            context.Session[CartSessionKey] =
                context.User.Identity.Name;
        }
        else
        {
            // Generate a new random GUID using System.Guid class
            Guid tempCartId = Guid.NewGuid();
            // Send tempCartId back to client as a cookie
            context.Session[CartSessionKey] = tempCartId.ToString();
        }
    }

    return context.Session[CartSessionKey].ToString();
}        

对在 asp.net 核心中使用 HttpContextBase 的工作有任何帮助吗?以上是我创建购物车的示例代码。

【问题讨论】:

  • 可以使用 HttpContextBase abstractContext = new System.Web.HttpContextWrapper(context);
  • @Tomato32 在 ASP.NET Core 中没有 System.Web
  • 您是在控制器之外执行此操作吗?
  • 试试这个答案enter link description here
  • 我不知道它是否重要,但不保证 guid 是随机的,它们只保证是唯一的。

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


【解决方案1】:

在 ASP.NET Core 中没有 HttpContextBaseHttpContext 已经是一个抽象类(参见 here),它在 DefaultHttpContext 中实现(参见 GitHub)。只需使用HttpContext

【讨论】:

  • public string GetCartId(HttpContext context) 这行得通。
  • 将其标记为已接受,如果它解决了您的问题,则它不会再出现在“未回答”部分中
  • 链接已失效。
  • @Jeppe:链接已更新并固定到 2.2 版本
【解决方案2】:

我不得不像下面这样修改

public string GetCartId(HttpContext context)
{
    if (context.Session.GetString(CartSessionKey) == null)
    {
        if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
        {
            context.Session.SetString(CartSessionKey, context.User.Identity.Name);
        }
        else
        {
            var tempCartId = Guid.NewGuid();
            context.Session.SetString(CartSessionKey, tempCartId.ToString());
        }
    }

    return context.Session.GetString(CartSessionKey);
}

它可能对某人有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-20
    • 2012-07-14
    • 2011-03-10
    • 2017-08-13
    • 2019-08-31
    • 1970-01-01
    • 2017-06-16
    相关资源
    最近更新 更多