Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement HttpContext in .net core 2.0?

I have been trying to implement the http context in the ASP.NET MVC and system.web ,it would just use allow me to use HttpContext.Current to access the context . Anyway I started by injecting the IhttpcontextAccessor in the configureService method in the StartUp Class. I am posting this to see if anyone has implemented this using .Net Core 2.0. If so, please feel free to share the knowledge. Thanks in advance.

 services.AddSingleton<HttpContextAccessor, HttpContextAccessor>();
like image 787
cedPound Avatar asked Dec 03 '22 12:12

cedPound


2 Answers

If you need it from a Controller, then just use HttpContext, as Muqeet's answer says.

If you do need to inject it, then you're on the right track with AddSingleton, but you have a slight typo:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Notice the I in the first type.

Then set up your constructor:

public class UserService : IUserService {
    private readonly HttpContext _context;

    public UserService(IHttpContextAccessor httpContextAccessor) {
        _context = httpContextAccessor.HttpContext;
    }
}

Then you can use context anywhere else in your class.

That's the basics of dependency injection. AddSingleton makes it available for injection. Then you ask for it where you need it by adding it to your constructor.

That article that Maarten linked to in his comment explains in more detail.

like image 64
Gabriel Luci Avatar answered Dec 12 '22 17:12

Gabriel Luci


In Controllers

Looking at your code example it looks like you are trying to get the HttpContext information within a controller. You DO NOT need to inject HttpContextAccessor, as HttpContext is already available for you as a property on the Controller. You can use it as you would any other property.

Example

[Authorize]
public async Task<IActionResult> MySecureAction()
{
   _logger.LogDebug($"Logged in User is {HttpContext.User.Identity.Name}");
   return OK();
}

In Services

If you are trying to get access to the HttpContext object in a service then you would constructor inject the IHttpContextAccessor.

Asp.Net Core 2.1

In the upcoming release for ASP.NET Core 2.1, there will be a helper extension method AddHttpContextAccessor available for you to add it to the service collection properly.

like image 38
Muqeet Khan Avatar answered Dec 12 '22 17:12

Muqeet Khan