【问题标题】:'IApplicationBuilder' does not contain a definition for 'UseSession'“IApplicationBuilder”不包含“UseSession”的定义
【发布时间】:2018-07-22 13:05:09
【问题描述】:

我正在使用之前使用 Core 1.0 的 ASP.NET Core 2.0 构建应用程序。迁移后一切似乎都运行良好,但是当我尝试使用 Session 方法 app.UseSession() 时,它会引发以下错误:

“IApplicationBuilder”不包含“UseSession”的定义,并且找不到接受“IApplicationBuilder”类型的第一个参数的扩展方法“UseSession”(您是否缺少 using 指令或程序集引用?)

我尝试从 NuGet 安装 ASPNETCore.Session 包,但不能。

谁能帮我找出问题的根本原因?

【问题讨论】:

  • 你有提到Microsoft.AspNetCore.Session Nuget 包吗?
  • 我尝试从 nuGet 安装引用,但它正在回滚。不让我安装它
  • 那你需要先解决这个问题。
  • @DavidG 这就是我无法指出的。它在 errorList 中显示另一个错误,但这是由于 tsconfig.json 文件,显示“已为以下项目禁用 JavaScript 语言服务”。我在这里看到了一个类似的问题,它只是给了我更多的错误,同时将它附加到项目的根目录。 “找不到 tsconfig.json 的源输入”
  • 这只是您的项目需要修复的更多问题。在询问您为什么不能将会话添加到您的项目之前,先将它们整理出来。

标签: asp.net-core asp.net-core-2.0 asp.net-core-mvc-2.0


【解决方案1】:

首先将 Session Service 注入到您的 ConfigureServices 方法中:

services.AddSession(options =>
{
      // Set a short timeout for easy testing.
      options.IdleTimeout = TimeSpan.FromSeconds(2400);
      options.Cookie.HttpOnly = true;
});

然后在Configure方法中使用app.UseSession();

在 ASP.NET Core Session 不支持通用数据类型你需要添加这个扩展

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

public static class SessionExtensions
{
    public static void Set<T>(this ISession session, string key, T value)
    {
        session.SetString(key, JsonConvert.SerializeObject(value));
    }

    public static T Get<T>(this ISession session,string key)
    {
        var value = session.GetString(key);
        return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
    }
}

并使用它:

public IActionResult SetDate()
{
    // Requires you add the Set extension method mentioned in the article.
    HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now);
    return RedirectToAction("GetDate");
}

public IActionResult GetDate()
{
    // Requires you add the Get extension method mentioned in the article.
    var date = HttpContext.Session.Get<DateTime>(SessionKeyDate);
    var sessionTime = date.TimeOfDay.ToString();
    var currentTime = DateTime.Now.TimeOfDay.ToString();

    return Content($"Current time: {currentTime} - "
                 + $"session time: {sessionTime}");
}

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 2019-09-22
    • 2017-07-31
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多