gpt4 book ai didi

c# - .NET Core IHttpContextAccessor 问题

转载 作者:行者123 更新时间:2023-11-30 20:18:54 32 4
gpt4 key购买 nike

我有静态助手类

public static class Current
{
public static string Host
{
get { return "httpContextAccessor here"; }
}
}

如何访问 Host 属性中的当前 HttpContext?

最佳答案

你不能也不应该。这完全违背了拥有依赖注入(inject)系统的全部目的。静态类(用于运行时数据或服务定位器)是一种反模式。

在 ASP.NET Core 中你必须注入(inject) IHttpContextAccessor在你需要的类里面。你可以制作一个非静态类并按照以下方式做一些事情:

public class RequestInformation : IRequestInformation
{
private readonly HttpContext context;

public RequestInformation(IHttpContextAccessor contextAccessor)
{
// Don't forget null checks
this.context = contextAccessor.HttpContext;
}

public string Host
{
get { return this.context./*Do whatever you need here*/; }
}
}

然后在你的类库中注入(inject)它:

public class SomeClassInClassLibrary
{
private readonly IRequestInformation requestInfo;

public SomeClassInClassLibrary(IRequestInfomation requestInfo)
{
// Don't forget null checks
this.requestInfo = requestInfo;

// access it
var host = requestInfo.Host;
}
}

请注意您的 SomeClassInClassLibrary必须用 Scoped 解决或 Transient模式,它不能是 Singleton ,因为 HttpContext仅在请求期间有效。

或者如果SomeClassInClassLibrary必须是单例,你必须注入(inject)一个工厂并解决 IRequestInformation按需(即在 Action 中)。

最后但同样重要的是,IHttpContextAccessor默认情况下未注册。

IHttpContextAccessor can be used to access the HttpContext for the current thread. However, maintaining this state has non-trivial performance costs so it has been removed from the default set of services.

Developers that depend on it can add it back as needed: services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

来源:The IHttpContextAccessor service is not registered by default

关于c# - .NET Core IHttpContextAccessor 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40303982/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com