I have a static class User
with a static property Username
. I set this property in a middleware on each url request. Then i show the Username
to user in the header of site.
On every request, this static property is set and then shown in the view. I am assuming that each request will have it's own (correct) value in the property and the value does not get shared between different requests?
So, if request one has value adam
and request 2 has value john
, adam will see adam and john will see john in the header? This is working okay in my app but just want to make sure that conceptually it is right?
This as you have already been informed is a good candidate for HttpContext.Items
with a unique object key to avoid key collisions. As each context is unique for each request they will allow the values to not get shared between the different requests. You are not setting the value as a static value on the middle ware but on the current request context.
public class SampleMiddleware {
public static readonly object SampleKey = new Object();
public async Task Invoke(HttpContext httpContext) {
httpContext.Items[SampleKey] = "some value";
// additional code omitted
}
}
Other code can access the value stored in
HttpContext.Items
using the key exposed by the middleware class:
public class HomeController : Controller {
public IActionResult Index() {
string value = HttpContext.Items[SampleMiddleware.SampleKey];
}
}
Reference Introduction to session and application state in ASP.NET Core
So only the key is static but the value set in the items will be unique for each request. That means in your case that if request one has value adam
and request 2 has value john
, adam will see adam
and john will see john
in the header
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