控制器外部类中的Context.Session [英] Context.Session in a Class outside Controller

查看:68
本文介绍了控制器外部类中的Context.Session的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在控制器中,我当前正在使用Context.Session.GetString(*KEY*);
我有一个需要从会话中存储的一些值中读取的类

In the controller I'm currently using Context.Session.GetString(*KEY*);
I have a class that needs to read from a few values stored in the session

我曾经用过这个HttpContext.Current.Session[*KEY*].

我曾经尝试过在Stackoverflow和MSDN中进行搜索,但是没有运气.

I've tried searching in Stackoverflow and MSDN with no luck.

推荐答案

HttpContext.Current在ASP.NET 5中不再存在,但是有一个新的IHttpContextAccessor可以注入依赖项并用于检索依赖项.当前HttpContext: https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting.Abstractions/IHttpContextAccessor.cs

HttpContext.Current doesn't exist anymore in ASP.NET 5, but there's a new IHttpContextAccessor that you can inject in your dependencies and use to retrieve the current HttpContext: https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting.Abstractions/IHttpContextAccessor.cs

public class MyComponent : IMyComponent {
    private readonly IHttpContextAccessor contextAccessor;

    public MyComponent(IHttpContextAccessor contextAccessor) {
        this.contextAccessor = contextAccessor;
    }

    public string GetDataFromSession() {
        return contextAccessor.HttpContext.Session.GetString(*KEY*);
    }
}

这篇关于控制器外部类中的Context.Session的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆