在ASP.NET Core的会话中存储模型类

时间:2019-11-28 17:26:02

标签: asp.net-core

嗨,有人可以帮我提供代码,将模型类存储在Asp.NET Core的会话中

1 个答案:

答案 0 :(得分:1)

ASP.NET Core会话对象具有3种方法来设置会话值,分别是SetSetInt32SetStringSet方法接受一个字节数组作为参数,其中SetInt32SetString方法是Set方法的扩展方法。

要存储复杂的对象,我们需要创建一个扩展类以在会话中存储和检索对象。在这里,对象被转换为JSON并存储为字符串。以后,将其作为字符串检索并反序列化为原始对象。喜欢,

public static class SessionExtensions
{
  public static void SetObject(this ISession session, string key, object value)
  {
    session.SetString(key, JsonConvert.SerializeObject(value));
  }

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

现在,您可以存储复杂的对象,如下所示:

var cart = new Cart { Id = 1, Name = "Cart1" };
HttpContext.Session.SetObject("Cart", cart);

并按以下方式获取它们:

var obj=HttpContext.Session.GetObject<Cart>("Cart");

Startup.cs

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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddSession(opts =>
        {
             opts.Cookie.IsEssential = true;// make the session cookie Essential
        });
    }

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

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