【发布时间】:2019-03-21 18:12:48
【问题描述】:
我正在编写以下代码:Access the current HttpContext in ASP.NET Core
我收到错误消息。我将如何解决这个问题?
另外,接口IMyComponent 的代码是什么?只是想确定它的正确性。
错误:
类型或命名空间 IMyComponent 找不到 当前上下文中不存在名称“KEY”。
public class MyComponent : IMyComponent
{
private readonly IHttpContextAccessor _contextAccessor;
public MyComponent(IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
}
public string GetDataFromSession()
{
return _contextAccessor.HttpContext.Session.GetString(*KEY*);
}
}
【问题讨论】:
-
请提供minimal reproducible example。
*KEY*不是有效的 C#。 -
我收到了上面堆栈溢出问题的代码,猜猜我的问题应该是什么Key?
-
根据您的问题,我认为您不需要
GetString()。如果它是您想要的HttpContext,您应该可以使用_contextAccessor.HttpContext做得很好。该示例仅显示了如何访问存储在 Session 中的字符串。 -
我建议查看docs。
Key应该是一个字符串,用于标识您已保存到会话中的项目。IMyComponent是MyComponent的接口。 -
是否在依赖注入块中添加了 MyComponent 和 IMyComponent 的设置?
标签: c# asp.net-core .net-core asp.net-core-mvc .net-core-2.0