且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 ASP.NET Core 中获取 HttpContext.Current?

更新时间:2023-02-16 09:00:18

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

As a general rule, converting a Web Forms or MVC5 application to ASP.NET Core will require a significant amount of refactoring.

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

HttpContext.Current was removed in ASP.NET Core. Accessing the current HTTP context from a separate class library is the type of messy architecture that ASP.NET Core tries to avoid. There are a few ways to re-architect this in ASP.NET Core.

您可以通过任何控制器上的 HttpContext 属性访问当前的 HTTP 上下文.与您的原始代码示例最接近的是将 HttpContext 传递到您正在调用的方法中:

You can access the current HTTP context via the HttpContext property on any controller. The closest thing to your original code sample would be to pass HttpContext into the method you are calling:

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参数

如果您正在编写 自定义ASP.NET Core 管道的中间件,当前请求的 HttpContext 会自动传递到您的 Invoke 方法中:

HttpContext parameter in middleware

If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext is passed into your Invoke method automatically:

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

HTTP 上下文访问器

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

HTTP context accessor

Finally, you can use the IHttpContextAccessor helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.

在你的构造函数中请求这个接口:

Request this interface in your constructor:

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

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

You can then access the current HTTP context in a safe way:

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

IHttpContextAccessor 默认情况下并不总是添加到服务容器中,所以为了安全起见,在 ConfigureServices 中注册它:

IHttpContextAccessor isn't always added to the service container by default, so register it in ConfigureServices just to be safe:

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

    // Other code...
}