I need to somehow attach my custom data to the HttpRequest
being handled by my IIS custom modules - so that code that runs in earlier stages of IIS pipeline attaches an object and code that runs in later stages can retrieve the object and use it and no other functionality of IIS pipeline processing is altered by adding that object.
The data needs to persist within one HTTP request only - I don't need it to be stored between requests. I need it to be "reset" for each new request automatically - so that when a new request comes it doesn't contain objects my code attached to the previous request.
Looks like HttpContext.Items
is the way to go, although MSDN description of its purpose is not very clear.
Is using HttpContext.Current.Items
the way to solve my problem?
Instead of using HttpContext. Current , use the HttpContext provided as a property on the Page or Controller , or even better, you can simply use the Session property.
Current property, instead it is available in the HttpContext class in ASP.Net Core applications. Session can be enabled using the Configure method. Inside this method, you will have to call the UseSession method of the app object. Note: It is mandatory to call the UseSession method before the UseMvc method.
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... }
HttpRequest is a subset of HttpContext . In other words, the HttpContext includes the response, the request, and various other data that's not relevant to a specific request or response; such as the web application, cached data, server settings and variables, session state, the authenticated user, etc.
This should work - I have done this in a project before.
I have a class which has a static property like this -
public class AppManager
{
public static RequestObject RequestObject
{
get
{
if (HttpContext.Current.Items["RequestObject"] == null)
{
HttpContext.Current.Items["RequestObject"] = new RequestObject();
}
return (RequestObject)HttpContext.Current.Items["RequestObject"];
}
set { HttpContext.Current.Items["RequestObject"] = value; }
}
}
And then RequestObject contains all my custom data so then in my app I can do
AppManager.RequestObject.CustomProperty
So far I have not come across any issues in the way HttpContext.Items works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With