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

查看:32
本文介绍了在 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 中不再存在,但有一个新的 IHttpContextAccessor 您可以将其注入您的依赖项并用于检索当前的HttpContext:

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天全站免登陆