当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net core Session的测试使用心得

asp.net core Session的测试使用心得

2018年05月05日  | 移动技术网IT编程  | 我要评论

斯德哥尔摩天气,你的温柔上司,醋泡鸡蛋祛斑小窍门

sp.net-core中Session是以中间件的形式注册使用的。不比asp.net中的使用,直接使用Session就行。

首先在.net-core框架中注入Session中间件,首先在ConfigureServices中注入Session服务。但是,我们还需要注册内存服务。将Session存储到内存中,代码如下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddDistributedMemoryCache();
    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromSeconds(1 * 60);
    });
}
View Code

接下来就是使用了。我们在表示HTTP管道的Configure中使用Session:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseSession();
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

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

我一开始并没有注意顺序,在这里的使用一定要注意顺序,如果顺序不当,会导致Session的使用出问题,但是并不会报错。
接下来就可以使用了。在Controller中:

public class HomeController : Controller
{
    string ss = "dasdas";
    public IActionResult Index()
    {
        if (HttpContext.Session.GetString(ss) == null)
        {
            HttpContext.Session.SetString(ss, "Added into Redis");
            ViewData["ewq"] = "Empty";
        }
        else
        {
            string s = HttpContext.Session.GetString(ss);
            ViewData["ewq"] = s;
        }
        return View();
    }

    public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";

        string s = HttpContext.Session.GetString(ss);
        ViewData["das"] = s;

        return View();
    }
}
View Code

一般来讲,到这里就可以了。但是我遇到了问题,困扰了我一上午。
我一开始是按照网上的配置和官网的资料来做的。但是运行死活就是不出来结果,后来改了下Configure里的UseSession方法的顺序。还是不行,刷新了几下同时将Get和Set的操作写在同一个Action里面,然后就可以了。我开始怀疑是不是Session丢失了。因为将Session存储到内存里面还得使用中间件,我怀疑asp.net-core的这种以中间件方式丢失Session的概率比较大。后来又尝试了分开来,写在不同的action里面,结果却是可以啦。
还是有必要研究下asp.net-core引入内存存储的原理的。
那么如何将session存储到redis呢。对于redis在asp.net-core的使用,请看<<.net-core-Redis分布式缓存客户端实现逻辑分析及示例demo>>。我们将AddDistributedRedisCache替换成AddDistributedMemoryCache,就可以啦。

代码demo地址: 链接:https://pan.baidu.com/s/1IqYiinVLzoz7vEl5tsnNEA 密码:gxe4

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网