提问人:Manib 提问时间:11/6/2023 最后编辑:Manib 更新时间:11/6/2023 访问量:28
IHttpContextAccessor.HttpContext 为 null WebForms
IHttpContextAccessor.HttpContext is null WebForms
问:
当我将 API 从 .NET Framework 4.8 调用到 .NET Core 时,我一直在尝试使用 IHttpContextAccessor.HttpContext 读取当前的 HttpContext。
我已将其添加到服务中:
services.AddHttpContextAccessor()
services.AddTransient<IService, Service>();
我在类中获得了 HttpContextAccessor,但 HttpContext 始终为 null:
页:
Private ReadOnly service As IService
Private httpContextAccessor As Microsoft.AspNetCore.Http.IHttpContextAccessor
Public Sub New(ByVal service As IService, ..., httpContextAccessor As IHttpContextAccessor)
Me.service = service
...
Me.httpContextAccessor = httpContextAccessor'<-- in debug mode I can see that HttpContext is null here also
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Public Async Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
Dim httpContext = httpContextAccessor.HttpContext '<--this is null
Dim results = await service.Method()
End Sub
服务业:
private readonly IHttpContextAccessor httpContextAccessor;
public Service(..., IHttpContextAccessor httpContextAccessor,...)
{
this.httpContextAccessor = httpContextAccessor; //<-- in debug mode I can see that HttpContext is null here also
}
public async Task<List<ModelDTO>> Method()
{
var httpContext = httpContextAccessor.HttpContext; //<-- Also null here.
...
}
如果它在那里不为空,我会将其从页面传递到服务。我已经读过一些关于它的东西,但无法弄清楚这一点。
例如
在这里 - 我尝试更改按钮,使其不是异步的,并且希望在进入方法之前填充 httpContext,但事实并非如此。
我还看到了一些关于如何实现 IHttpContextAccessor 的建议,我认为我通过复制它正确地完成了它。
答: 暂无答案
评论