HaBo HaBo - 1 year ago 540
ASP.NET (C#) Question

How to get HttpContext.Current in ASP.NET Core?

We are currently rewriting/converting our ASP.NET WebForms application using ASP.NET Core. Trying to avoid re-engineering as much as possible.

There is a section where we use

in a class library to check the current state. How can I access
in .NET Core 1.0?

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

I need to access this in order to construct current application host.

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

Answer Source

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

Getting HttpContext.Current isn't possible, because 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.

In ASP.NET Core, you can access the current HTTP context from a controller using HttpContext. The closest thing to your original code sample would be to pass the HttpContext into the method you are calling:

public class HomeController : Controller
    public IActionResult Index()

        // Other code

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

    // Other code

It's also possible to get the context using IHttpContextAccessor from the ASP.NET Core dependency injection system. If you have a controller or middleware function that requests the interface from the service container:

public MyMiddleware(IHttpContextAccessor httpContextAccessor)
    _httpContextAccessor = httpContextAccessor;

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

var context = _httpContextAccessor.HttpContext;

Since IHttpContextAccessor isn't added to the service container by default, you'll have to register it:

public void ConfigureServices(IServiceCollection services)
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // Other code...