本文介绍了在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!