在ASP.NET Core中访问当前的HttpContext [英] Access the current HttpContext in ASP.NET Core

查看:72
本文介绍了在ASP.NET Core中访问当前的HttpContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以静态方法或实用程序服务访问当前的HttpContext.

I need to access current HttpContext in a static method or a utility service.

使用经典的ASP.NET MVC和System.Web,我将只使用HttpContext.Current静态访问上下文.但是如何在ASP.NET Core中做到这一点?

With classic ASP.NET MVC and System.Web, I would just use HttpContext.Current to access the context statically. But how do I do this in ASP.NET Core?

推荐答案

HttpContext.Current在ASP.NET Core中不再存在,但是有一个新的

HttpContext.Current doesn't exist anymore in ASP.NET Core but there's a new IHttpContextAccessor that you can inject in your dependencies and use to retrieve the current HttpContext:

public class MyComponent : IMyComponent
{
    private readonly IHttpContextAccessor _contextAccessor;

    public MyComponent(IHttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
    }

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

这篇关于在ASP.NET Core中访问当前的HttpContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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