如何在 ASP.NET Core 中获取 HttpContext.Current? [复制]

2023-12-28

我们目前正在使用 ASP.NET Core 重写/转换我们的 ASP.NET WebForms 应用程序。尽量避免重新设计。

有一个部分我们使用HttpContext在类库中检查当前状态。我怎样才能访问HttpContext.Current在 .NET Core 1.0 中?

 var current = HttpContext.Current;
     if (current == null)
      {
       // do something here
       // string connection = Configuration.GetConnectionString("MyDb");
      }

我需要访问它才能构建当前的应用程序主机。

$"{current.Request.Url.Scheme}://{current.Request.Url.Host}{(current.Request.Url.Port == 80 ? "" : ":" + current.Request.Url.Port)}";

作为一般规则,将 Web 窗体或 MVC5 应用程序转换为 ASP.NET Core将需要大量的重构。

HttpContext.Current已在 ASP.NET Core 中删除。从单独的类库访问当前 HTTP 上下文是 ASP.NET Core 试图避免的混乱架构类型。有几种方法可以在 ASP.NET Core 中重新构建它。

HttpContext 属性

您可以通过以下方式访问当前的 HTTP 上下文HttpContext任何控制器上的属性。与原始代码示例最接近的事情是通过HttpContext进入您正在调用的方法:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        MyMethod(HttpContext);

        // Other code
    }
}

public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
    var host = $"{context.Request.Scheme}://{context.Request.Host}";

    // Other code
}

中间件中的 HttpContext 参数

如果你正在写自定义中间件 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware?tabs=aspnetcore2x#writing-middleware对于 ASP.NET Core 管道,当前请求的HttpContext被传递到你的Invoke自动方法:

public Task Invoke(HttpContext context)
{
    // Do something with the current HTTP context...
}

HTTP 上下文访问器

最后,您可以使用IHttpContextAccessor帮助程序服务,用于获取由 ASP.NET Core 依赖注入系统管理的任何类中的 HTTP 上下文。当您的控制器使用公共服务时,这非常有用。

在构造函数中请求此接口:

public MyMiddleware(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

然后您可以以安全的方式访问当前的 HTTP 上下文:

var context = _httpContextAccessor.HttpContext;
// Do something with the current HTTP context...

IHttpContextAccessor默认情况下并不总是添加到服务容器中,因此将其注册到ConfigureServices为了安全起见:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    // if < .NET Core 2.2 use this
    //services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // Other code...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 ASP.NET Core 中获取 HttpContext.Current? [复制] 的相关文章