.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Singleton, Depedency Injection, HttpContext.Current.Cache or something else?

Posted By:      Posted Date: October 18, 2010    Points: 0   Category :ASP.Net

I'm currently writing a webapp in MVC where I need to have a Request ID number for each submission that users send in. I originally wrote the class using a Singleton pattern which would contain "private static List<Request>" and then public accessor methods allow the list to be manipulated, updated, etc. -- So when hitting a new request page, the user would be assigned a new unique request ID and this would ID would be stored in the List<Request> of the Singleton with status, etc. and stay with them until they close the window or complete the request. So it would be a unique request number, but also give me a unique way of controlling the session and preventing double submissions or re-submissions of the same request.

I thought that this was brilliant until it was explained to me on StackOverflow that each page request is started in its own process and runs to completion and then the process dies, and the singleton with it. So with each new page request starts a new process with no knowledge of the previous singleton that was in memory.

The smart solution would be to store this in a DB, but unfortunately, I have none immediately available to me at the moment, so I'm storing the very last Request ID number in web.config. It's a hack, I realize...

So because of the way MVC works, it seems that Singleton and Static Clas

View Complete Post

More Related Resource Links

Intercept (and process) httpcontext.current.cache methods


Anyone know of a way (and how) I can intercept calls to the httpcontext.current.cache methods so that I can do some extra processing?

For example, when someone calls:

httpContext.Current.Cache.Add("some key", objSomeObject, Nothing, System.DateTime.Now.AddMinutes(63), Cache.NoSlidingExpiration, Caching.CacheItemPriority.NotRemovable, Nothing)
I want to be able to Intercept that call and find out:
1. What the "some key" value was AND
2. What the expiration value was.
All without having to filter through tons of code and change the calls.
PLUS, I don't want to have to rely on various developers compliance with inserting a call to
the tracking routine: if they use Cache.Add, my code gets called and I know what was passed.

Users getting logged out because HttpContext.Current is null


We've  been trying to fix this one for a couple years, and I'm just out of ideas, so any help is really appreciated!

We've got a fairly large, complex web application that uses Forms Authentication to authenticate users.  Throughout the application we store and retrieve information about users in the Session object, and in some cases in cookies.  In a couple places we check for the existence of the context, and if it's null we send the user back to the login page to re-establish the session. 

Just a quick run-down of this web app: C#, .NET 3.5, IIS 6, ASP.NET State Service to manage session

As for the session timer, we use our own home-grown timer, which is basically a client-side timer, which is backed up by a check to the SQL database to see when their last activity was.  This seems to work well for us.  It's not perfect, but it allows us to notify the user before the session times out, and allows us to be certain we're not logging a user out before their 60 minutes of inactivity is up.

What's happening is that certain users are being logged out after just a few minutes.  We've eliminated the timer as a cause and believe what's happening is the HttpContext.Current is null, so the user is logged out.  We do not know why the HttpContext.Current is null, and I underst


I am using Forms  Authentication. I set the cookie when user logs in. Welcome text =  HttpContext.Current.User.Identity.Name Logout = Session.Abandon and Session.Clear() Now when I logon using different user name i still see my previous login name when I do" HttpContext.Current.User.Identity.Name  

HTTPContext.Current.Session losing the variable sporatically

I have noticed a strange behaviour in my ASP.net 2.0 application. I have some logic in my aspx page that accesses some Session variables fine, then accesses some app_code and most of the time the HTTPContext.Current.Session returns the variable back fine.  However, I have noticed that sometimes this Session returns null, like it has lost it's "pointer" to the current HTTPContext. Is this a known bug, has anyone seen something like this before?   Any help would be appreciated, thanks, Mark. 

HttpContext.Current is null

I have an intermittent issue where HttpContext.Current is null.  I do have aspNetCompatibilityEnabled="True".  I can duplicate it by restarting the webservice and make the request.  The first request has the HttpContext.Current set to null but subsequent requests have the proper HttpContext.  I've done some tracing and the messages are exactly the same. What else is weird is that the HttpContext is NOT null in my global.asax but by the time it hits my custom UsernamePasswordValidator, it is set to null.   Any ideas on what i'm doing wrong? HttpRequest from tracing: <HttpRequest> <Method>POST</Method> <QueryString></QueryString> <WebHeaders> <Cache-Control>no-cache</Cache-Control> <Connection>Keep-Alive</Connection> <Content-Length>799</Content-Length> <Content-Type>text/xml; charset=utf-8</Content-Type> <Accept>*/*</Accept> <Accept-Encoding>identity</Accept-Encoding> <Host>mydomain.com</Host> <User-Agent>Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E; InfoPath.2)</User-Agent> <SOAPAction>"http://tempuri.org/ICategoryService/GetAvailablePickList"</SOAPAction> </WebHeaders> </Htt

httpcontext.current.user.identity.isauthenticated always false

Dear, please help me, I create two pages, the first one is the login page with user name and password textboxes - (not asp login control) , when clicking login button I check the login authentication, if it is true redirect to default page. in the default page if !IsCallBack then i check httpcontext.current.user.identity.isauthenticated if it is false i redirect the user to the login page. but my problem is that the httpcontext.current.user.identity.isauthenticated is always false. Below the section of authentication in web config < <authentication mode="Forms">forms loginUrl ="FrmUserLogin.aspx"  protection ="All"  timeout ="1"  name ="LoginRedirectCallback"  path ="/LoginRedirectCallback"  requireSSL ="false"  slidingExpiration ="true"  defaultUrl ="FrmDBLoginConfigaspx.aspx"  cookieless ="UseDeviceProfile"   < < </   </ </enableCrossAppRedirects ="false">credentials passwordFormat="Clear">user name ="admin" password ="admin"/>credentials>forms>authentication> thank you for any help.   Best Regards,


Hello, everyone! Well, I made some researches to discover how can I use session variables in App_code. A lot of sites show me answer is use HttpContext.Current.Session. But I´m having following error: The name 'HttpContext' does not exist in the current context. What can I do?

redirectMode="ResponseRewrite" disables HttpContext.Current.Session



we render a nice error page which uses quite a lot of code in the background. I tried adding redirectMode="ResponseRewrite" to the customErrors section in the web.config, but then the framework returns null from HttpContext.Current.Session. Therefore some of our code does not work anymore. When redirectMode is not set or set to ResponseRedirect then HttpContext.Current.Session is set.

How can we circumvent this?



HTTPContext.Current.Session is NULL in SharePoint 2007 (MOSS)


For some strange reason HTTPContext.Current.Session is null in SharePoint 2007 web application.

Session is enabled everywhere and used to work so its not a setup issue. Something got corrupted at some point either via patches or something...

Doing "Reset To Definition" fixes the issue, but I can't do that in production environment and what is reset to definition has to do with session being null?

Searching on the web found a post from someone having same exact issue:


I need to know how to FIX this w/o doing complete "Reset To Definition".

Why do you cast HttpContext.Current.Handler to a page?


I am writing a class (outside of the deafult page webform) and it needs access to a mschart.  The chart is called "Chart1".

I discovered on other forums that in order for a class to access the webform control, you do the following:

System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;

Chart Chart1 = (Chart)page.FindControl("Chart1");

But can someone tell me what does the first line do and why does it work?  What is it trying to do?  Why is it setting the context.current.handler to page? and why does it need to be cast to a page?

Secondly, why can't I create the page object by referencing the page class name, which is _Default in this case? (public partial class _Default : System.Web.UI.Page)

HttpContext.Current is giving wrong user information



I have used IIdentity WinId = HttpContext.Current.User.Identity; to get user information for the logged in user, but out of 5 user one user is getting other user's details. please suggest me how to sort out this issue.

I am not storing this details nor i processed before displaying it, i simply get value through above line and displaying it in the message box. So no question of overwriting by cookies or any other processes.



Alternative to HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"]

So I've got this Class Library I built, and I use this:

HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"].ToLower() to get the application path/working directory when the DLL is consumed/excecuted by a client project. It works great. The problem is when I deploy the Class/DLL as a WCF service, this line of code generates the error "Object not set to an instance of an object".

 any ideas how to fix this? or an alternative to this? I need to get the path/folder of the application.

HttpContext.Current is null - when HttpContext.Current.Request.ServerVariables["SERVER_PORT"] is us


HttpContext.Current  is null - when HttpContext.Current.Request.ServerVariables["SERVER_PORT"] and HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"] used.


This is in .asmx (2.0 framework) section. All i am trying is getting a server port # & validating some stuff.


Exception:  HttpContext.Current.Request.ServerVariables["SERVER_PORT"]    'System.Web.HttpContext.Current' is null   


Any thoughts?








I am using Principal class to get the user information

 HttpContext.Current.User.Identity.Name thro this i am getting doamin name and NT ID

So how can i extract User name and email from NT ID


HttpContext.Current.User.IsInRole() caching roles on server


I am trying to authorize my users against AD groups via HttpContext.Current.IsInRole() method. However the roles are getting cached on the server. Say support, I add myself to a group and verify against that group, I am not getting authorized. Is it possible to clear cache everytime before verification or as soon as i add myself to a group the cache should get cleared.

I do not use membership provider or any such config keys in my vs2008 project.

HttpContext.Current.Response.Redirect Not Working for Local Intranet Zone Sites


Hi All,

I have made this a seperate question as the original topic of another user who had a similiar issue was marked answered, however his answer is not mine.

In my infopath form, after the submit event, I am using HttpContext.Current.Response.Redirect(URL, false) to change the page.

I use an XPathNavigator to get the value for URL from a simple text box.

If i type in that text box http://www.google.com or http://www.hotmail.com, for instance, the page redirects perfectly.

However, if I type in a site address like http://intranet.mundaring.wa.gov.au or http://localhost for instance (which I need to), the form simply throws a critical error with no more detail than that.

The only pattern I can see is that the sites that DO work are in the Internet Zone, and all the sites that DO NOT work are all listed as Local Intranet sites.

I cannot change my local intranet sites as they are enforced by policy.

Please could somebody assist me with why this may be doing this. The form is opened from the intranet (a local site) so no zone change is taking place.




Are same the System.Web.HttpContext.Current.Session and normal Session?


Hi all,

I have used System.web.httpcontext.current.session and normal session in my web application

both sessions are having the same name.. but i can get the value from session["name"] not from System.web.httpcontext.current.session["name"]..

is there any problem..

I have used system.web.httpcontext.current.session in my class file..

session have use in my aspx.cs file..

supppose I need to check the session["name"] in my class file what should I do?

is there any diffreence between thease?



ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend