Home > Back-end >  How to add an object to HttpContext.Current so it is available later on in processing?
How to add an object to HttpContext.Current so it is available later on in processing?

Time:07-14

I need to add value to HttpContext.Current inside of controller action so it is later available without need of passing it directly to a method. How can I do it? I have action method:

  public async Task<IActionResult> Method([FromBody] MyRequestDto myRequest )

I want to add myRequest toHttpContext.Current so I can read it in the method that is not invoked from Method.

CodePudding user response:

You can store almost anything you like in the HttpContext.Items property.

For example:

var myThing = new Foo();
HttpContext.Items.Add("myFoo", myThing);

And later:

var myThing = HttpContext.Items["myFoo"];

Also note that in ASP.NET Core, HttpContext.Current isn't valid code anymore. You can access the context in a controller using this.HttpContext or elsewhere with dependency injection using the IHttpContextAccessor interface.

CodePudding user response:

In ASP.NET Core HttpContext.Current was removed. Inside the controller you can use ControllerBase.HttpContext property and add to it's Items property some value:

HttpContext.Items - Gets or sets a key/value collection that can be used to share data within the scope of this request.

public async Task<IActionResult> Method([FromBody] MyRequestDto myRequest)
{
    HttpContext.Items["test"] = myRequest;
}
  • Related