ASP CORE中关于HttpContext的注入

问题描述 投票:0回答:1

在我的 ASP CORE 项目中,我需要从名为 ObSessions 的自定义类访问 httpContext 对象。

感谢伟大的开发者社区,我找到了一个神奇的解决方案,但我不明白我的自定义类中的一行代码。

该行是: private static HttpContext _httpContext => new HttpContextAccessor().HttpContext;

我认识 javascript 中的 lambda 表达式或箭头函数...但是如何解释这一行? 我知道这个主题是关于 DI(直接注入)的,但是有人可以告诉我这段代码是否符合最新标准或者是访问当前上下文的最佳方式吗? 我可以比这种方式更好地访问当前用户会话吗? 我希望我的帖子可以帮助其他人 感谢您阅读我的文章。

这是我班级的代码:

public class ObSession
    {       
        public string name { get; set; }
        // ..other fields
        private static HttpContext _httpContext => new HttpContextAccessor().HttpContext;
        private class ObSession()
        {}

        public static ObSession CurrentSess
        {
            get
            {
                ObSession session = (ObSession)_httpContext.Session.GetObject("MySession");
                if (session == null)
                {
                    session = new ObSession();
                    _httpContext.Session.InitObjectStore();
                    _httpContext.Session.SetObject("MySession", session);
                }
                return session;
            }

        }
    }
asp.net-core dependencies
1个回答
0
投票

我找到了答案。 我想把它写在这篇文章中......也许它可以帮助某人。

该行称为“表达式体定义”,它是一个“语法糖”,请阅读此post。 事实上,这一行可以用这段代码替换(它有效)。 我澄清了我的问题。

private static HttpContext _httpContext
{
    get
    {
        return new HttpContextAccessor().HttpContext;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.