【问题标题】:HttpContext.Session not maintaining state [duplicate]HttpContext.Session 不维护状态 [重复]
【发布时间】:2019-03-07 03:47:57
【问题描述】:

我一直在网上找出我使用 HttpContext.Session 有什么问题。我设置会话时似乎正在设置会话,但在它离开功能后,我无法访问它。我检查了我的 Startup.cs 文件以确保所有内容都正确添加并安装了正确的 NuGet 包。

在我实际使用会话的控制器类中,我有以下代码:

    /// <summary>
    /// Check to see if user exists.  If yes, go to the administrator interface,
    /// else return to the login page.
    /// </summary>
    /// <param name="administrator"></param>
    /// <returns></returns>
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult AdminLogin([Bind("UserName", "Password")] Administrator administrator)
    {
        try
        {
            var admin = _context.Administrators.Where(x => x.UserName == administrator.UserName
                && x.Password == administrator.Password).FirstOrDefault();

            if (admin != null)
            {
                HttpContext.Session.SetString("IsAdmin", "true");
                _httpContextAccessor.HttpContext.Response.Cookies.Append("IsAdmin", "true");
            }

            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    /// <summary>
    /// Shows the administrator interface
    /// </summary>
    public IActionResult Index()
    {
        if (HttpContext.Session.GetString("IsAdmin") == "true"
            || _httpContextAccessor.HttpContext.Request.Cookies["IsAdmin"] == "true")
        {
            ViewData["isAdmin"] = "true";
            HttpContext.Session.SetString("IsAdmin", "true");
            ViewData["Title"] = "Administrator Page";
            ViewData["Message"] = "Administrator Page";
            return View();
        }
        else
        {
            return RedirectToAction("AdminLogin");
        }
    }

如您所见,我在 AdminLogin 函数中设置了一个会话变量 (IsAdmin),然后尝试在索引视图中访问该会话。我有 ValidateAntiForgeryToken,我认为这可能是我的问题,但即使我删除它,我的会话也不会持续存在。我也在尝试使用 cookie 作为解决方法,但这些也没有持续存在。如果有人愿意帮助我,我可以发布更多代码。如果我不能让它工作,我将不得不重新开始并且不使用 Asp.NET Core。我的应用程序的其余部分最终也必须使用会话。

这是我的 startup.cs,只是为了确保它确实设置正确...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using OM2018a.Data;
using Microsoft.EntityFrameworkCore;

namespace OM2018a
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<OM2018Context>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            // Add MVC services to the services container.
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(15);
            });

            services.AddHttpContextAccessor();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();

            // IMPORTANT: This session call MUST go before UseMvc()
            app.UseSession();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

【问题讨论】:

    标签: c# session asp.net-core persistence httpcontext


    【解决方案1】:

    我找到了答案! Session variable value is always getting null in ASP.NET Core 2.1

    我不得不更改选项。CheckConsentNeeded = context => true;为假,它起作用了!

    【讨论】:

    • 它有效!新的cookie .AspNetCore.Session 出现在请求中
    【解决方案2】:

    您必须将 Startup.cs 文件中的 options.CheckConsentNeeded = context =&gt; true; 更改为 options.CheckConsentNeeded = context =&gt; false;

    public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => false;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
    .....
    }
    

    就是这样。

    【讨论】:

      猜你喜欢
      • 2019-07-12
      • 1970-01-01
      • 2013-03-06
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多