【问题标题】:Session not working in ASP.Net Core Web API会话在 ASP.Net Core Web API 中不起作用
【发布时间】:2021-11-07 09:53:41
【问题描述】:

我正在尝试使用 ASP.NET Core Web API (.NET Core 3.1) 中的会话功能。作为测试,我将我的项目配置如下。

  1. 安装 NuGet 包Microsoft.AspNetCore.Session

  2. ConfigureServices中添加服务方法Startup.cs

services.AddDistributedMemoryCache();
services.AddSession();
  1. Configure 中使用会话Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseSession();
    
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
  1. 在我的控制器中的一个路由中设置会话变量。
HttpContext.Session.SetString("currentUser", "value1");

但是,我不断收到此错误。

{"type":"NullReferenceException","message":"未设置对象引用 到一个对象的实例。","stackTrace":" at MainRoute.cs:line 中的 Api.Routes.MainRoute.Handler(ILogger`1 logger) 16\n 在 Api.Controllers.MainController.MainRoute(字符串 授权)在 MainController.cs:line 264"}

我该如何解决这个问题?

【问题讨论】:

  • 请发布您的整个Configure 方法——因为app. 方法的调用顺序很重要。
  • 请发布NullReferenceException 的整个堆栈跟踪 - 是什么让您如此确定它与会话状态相关?
  • AddDistributedMemoryCache 分布式内存缓存? (例如 Redis、memcached 等)。相反,对于单个和较小的 Web 应用程序,您可能只需要 AddMemoryCache()
  • 我已经按照你说的做了。我使用了AddDistributedMemoryCache,因为它解决了像Unable to resolve service for type 'Microsoft.Extensions.Caching.Distributed.IDistributedCache' while attempting to activate 'Microsoft.AspNetCore.Session.DistributedSessionStore'.这样的错误
  • 请阅读Stackoverflow 中有关 API 会话的线程。希望对您有所帮助。

标签: c# asp.net-core-webapi .net-core-3.1


【解决方案1】:

我不确定,但this document 帮我设置了会话,这是我的启动文件:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromSeconds(10);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSession();
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-13
    • 2019-04-30
    • 1970-01-01
    • 2020-05-17
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多