Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net MVC - request-scoped global variable

Tags:

asp.net-mvc

I have a value which I want to be vaild during a single request. I am not using Session, as this would make the value global for the entire navigation session.

So I have put thie value in a static field of a class. Great, but then I discovered that such fields are even more global, that is, they stay set for the entire application! This means that there could be random interaction among navigation sessions.

So the question is: is there a safe place I can put a global variable, which will be

  • global throughout the request
  • reset after the request is completed
  • not affected by any other request, either of the same user or by other users

Thanks Palantir

EDIT I'll elaborate. I have a piece of code in my master page, which I need to hide on certain conditions, of which I am aware in the controller only. I thought about setting a static variable in the controller, which then would be queried by the master page, but now I see there could be a better way...

like image 586
Palantir Avatar asked Sep 29 '09 12:09

Palantir


People also ask

What are global variables in ASP NET?

ASP.NET Global Variables Example Use global variables in ASP.NET websites by specifying static fields. Global variables are useful in ASP.NET. They don't need to be copied and only one is needed in the website application.

What is the difference between global and static fields in ASP NET?

Global: Static fields and properties in ASP.NET are always global. Another copy is never created. You will not have duplication. Performance: Static fields are efficient in normal situations.

Should I use static fields for application objects in ASP NET?

A problem with the Application object in ASP.NET is that it requires casting to read its objects. This introduces boxing and unboxing. Static fields allow you to use generics. Is this recommended? Yes, and not just by the writer of this article.


2 Answers

Use HttpContext.Items - a per-request cache store. Check out this article on 4guysfromrolla for more details.

It should work fine in ASP.NET MVC. You may wish to derive your master page from a base class (either via code-behind or using the Inherits directive) and have a protected method on the base class that inspects HttpContext.Items and returns, e.g. true/false depending whether you want to display the conditional code.

like image 173
Dylan Beattie Avatar answered Sep 28 '22 05:09

Dylan Beattie


TempData lasts until the next request as already noted.

But there are also two other dictionaries scoped to the single request.

  • {Controller,ViewPage}.ViewData
  • Context.Items

To communicate from controller to (master) page ViewData is probably the better choice.

like image 34
Richard Avatar answered Sep 28 '22 04:09

Richard