Session in asp.net - asp.net

I need a detailed example about session in asp.net using c#
For example(using session in log in operation

The Session is the system in ASP.Net where you can save objects and variables User-based, so these items can be available across postbacks.
Adding a variable to the Session:
Session["key"] = myVar;
Retrieving a variable
myVar = Session["key"];
myVar = (MyType) Session["key"];
In the Session, you can save any .NET Framework type, But you should be very aware of the impact this design can weigh in your application, as this imposes scalability issues.
In the answer to this question there is an excellent utility class that can help you to abstract the session object, also take a look at it.

Sorry, not entirely sure what you're after with the login stuff, but using session is fairly trivial, the following two pages from MSDN should get you started:
How to: Save Values in Session State
How to: Read Values From Session State
If you've got the standard login controls on a page you can handle the LoggedIn Event to store additional details in the users Session State.

You might consider using Forms Authentication: http://msdn.microsoft.com/en-us/library/aa480476.aspx

Related

Using Multiple Cultures in .NET CORE 3.1 Web App

We have a web app that displays data from a couple of different web apps. In each of those web apps, the culture is configurable (it is set by a company admin at the app level for all users, not per user).
In our web app, we need to display the data from each of the other web apps, in the culture configured for that app. The only good news is that currently we don't display "mixed" data from both apps, in a single view. And generally, a controller and all of its actions will only work with data from a single app (meaning that all actions from that controller will use the same culture).
There are several things I'm struggling with:
Does .NET Core really not honor setting culture like in the old days? I've tried it but it doesn't work (unless I'm setting it in the wrong place in the pipeline).
Thread.CurrentThread.CurrentCulture = firstWebAppCultureInfo;
Thread.CurrentThread.CurrentUICulture = firstWebAppCultureInfo;
Does it really only check these to find and set the culture?
QueryStringRequestCultureProvider
CookieRequestCultureProvider
AcceptLanguageHeaderRequestCultureProvider
I know I could write a custom provider, but that wouldn't seem to help me. We already get the various culture settings for the apps, from a database and store them in session.
My first thought was to write out a Culture Cookie every time the user hits a controller. I'd read the culture from session and write the cookie. But there are a couple of issues I see with this.
Issue 1: If I write the cookie out in the controller action, it doesn't "take affect" the first time it is changed from one culture to another. Obviously the cookie has already been read and the culture has already been set for that request. I'm too late in the pipeline to do that.
I tried writing the cookie out in the constructor of the controller (or constructor of a base controller) but HttpContext is not yet set at that point (it is null).
I have worked a bit with Filters and I will write an Action Filter that writes the cookie to see if that works, but see Issue 2.
Issue 2: Another issue would surface if the user opened multiple instances of their browser. The last culture written will "win" I suspect. So if a user is displaying data in Culture fr-FR in one browser and en-US in another instance of a browser and navigates to a controller/view that writes that en-US cookie, and then from the other browser instance navigates to a page that is supposed to use the fr-FR culture, the user would get the en-US setting from the cookie and that's not acceptable.
I don't really want to use the QueryStringRequestCultureProvider, because having that show up in the url is ugly.
I'm definitely not an expert in this area.
What am I missing?
How would you all implement this?
Thanks in Advance.
UPDATE
I created an ActionFilter and TypeFilterAttribute that allows me to pass a parameter into the ActionFilter. Using the parameter I can decide which key to read from Session to give me the culture setting I've stored for each web app.
From there I can mark each controller with that attribute and the appropriate parameter to tell the action filter what culture to use (remember we don't mix data, so each controller displays views that show data from only one of the two web apps, not both).
In the ActionFilter I can look up the culture string from session and do the following and it works:
var ci = new CultureInfo(this.cultureSetting);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
While that is encouraging, it feels hacky. So please comment on the solution...
I'd like to find a way to do all of this in a BaseController or somewhere, so I wouldn't need to put attributes on all of our controllers.
But whatever I've tried in a base controller seems like it is either:
a) too late in the pipeline to set the culture for that request, or
b) too early in the pipeline to get access to httpcontext.
Thoughts? Ideas?
UPDATE 2
I guess overriding OnActionExecuting in my base controller lets me do the same things as the ActionFilter...
So I guess I have a solution, but if anyone has a better idea, I'm listening.
We decided to go with an ActionFilter for our solution, so we can mark Controllers and/or Actions with an Attribute that indicates which app we are getting data from, so we can apply that app's culture setting...

ASP.NET equivalent to JSF Session Bean

I'm fairly new to both JSF and ASP.NET, and as far as I can understand (correct me if I'm wrong), while using session scoped beans in JSF, data is stored on the server side temporarily, for the components. But in ASP.NET it seems that such temporary data is stored in a hidden field in the page itself, called Viewstate.
Am I right in assuming this? Is there anything in ASP.NET that'll automatically manage the data and store it server side in objects (like JSF does) ?
ASP.NET has support for both a Viewstate and a Session state. Here is a link to some info regarding session state.
http://msdn.microsoft.com/en-us/library/ms178581.aspx
I'd recommend that you try to avoid using the viewstate at all, and use the session state sparingly. You should strive to keep your ASP.NET applications as "stateless" as possible. Do not over-use the session state or you could experience scalability issues down the road. Consider the following alternatives.
https://web.archive.org/web/20211020145945/https://www.4guysfromrolla.com/webtech/041600-2.shtml
You can use ASP.NET Session State.
Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;
Where the data is actually stored (in memory, in a database) can be configured. Depending on your situation, it may be better to store state in the view. Using the view state would be better in any situation where a single user might have two browser windows open at the same time, and expect them to keep separate state, such as the current stage in a wizard workflow.

How can I throw an Exception if Session is written to in ReadOnly mode?

I would like to find a way to raise an exception if the Session is written to when in readonly mode. When EnableSessionState is set to "ReadOnly", values can still be put in Session, but the next request they will not be there. This seems somewhat dangerous.
One option is to create a helper class which we alway use to access session. However, this still leaves room for a developer to inadvertently use session directly, and fall into the "readonly" trap. Is there a way to create a CustomSessionStateDataStore that sits on top of the existing session code? I could not see an obvious way, and you can't inherit from System.Web.SessionState.SessionStateStoreData directly.
Thanks for any help
Session state is built atop the provider model so you could create a custom session provider, I imagine.
Here's an article that discusses the provider model from a high-level view: ASP.NET 2.0 Provider Model: Introduction to the Provider Model.
And here's an article that talks about the session state providers and shows how to create your own custom provider: Session State Providers.
I ended up implementing my own SessionStateModule to achieve what I needed. See this thread for more info: I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

Preserve Session Variables Across HttpHandlers

I have an ASP.NET application with 5 .ashx HTTPHandlers that implement IRequiresSessionState or IReadOnlySessionState.
Upon calling the first handler I create a variable and store it in the session.
When I call the next HttpHandler the variable is not available in the session object.
I am use context.Session.
I have a global.asax where I retrieve the sessionId.
Is there a way to preserve session variables across HttpHandlers or does each Handler get its own session?
HeartAttack has a good discussion of this here:
http://weblogs.asp.net/ashicmahtab/archive/2008/09/18/how-to-use-session-values-in-an-httphandler.aspx
Basically, you need to do something like:
public class MyHandler:IHttpHandler,IRequiresSessionState
HTH's.
This should maintain session state across handlers. That is, when you log in, you only have one session for all of your requests into that domain. I'd suggest verifying that you are really logged in. Cache of course will work because that is common to all sessions but much more expensive on the server because it does not easily go away.

What should I do if the current ASP.NET session is null?

In my web application, I do something like this to read the session variables:
if (HttpContext.Current.Session != null && HttpContext.Current.Session["MyVariable"] != null)
{
string myVariable= (string)HttpContext.Current.Session["MyVariable"];
}
I understand why it's important to check why HttpContext.Current.Session["MyVariable"] is null (the variable might not have been stored in the Session yet or the Session has been reset for various reasons), but why do I need to check if HttpContext.Current.Session is null?
My understanding is that the session is created automatically by ASP.NET therefore HttpContext.Current.Session should never be null. Is this assumption correct? If it can be null, does it mean I should also check it before storing something in it:
if (HttpContext.Current.Session != null)
{
HttpContext.Current.Session["MyVariable"]="Test";
}
else
{
// What should be done in this case (if session is null)?
// Is it possible to force the session to be created if it doesn't exist?
}
Yes, the Session object might be null, but only in certain circumstances, which you will only rarely run into:
If you have disabled the SessionState http module, disabling sessions altogether
If your code runs before the HttpApplication.AcquireRequestState event.
Your code runs in an IHttpHandler, that does not specify either the IRequiresSessionState or IReadOnlySessionState interface.
If you only have code in pages, you won't run into this. Most of my ASP .NET code uses Session without checking for null repeatedly. It is, however, something to think about if you are developing an IHttpModule or otherwise is down in the grittier details of ASP .NET.
Edit
In answer to the comment: Whether or not session state is available depends on whether the AcquireRequestState event has run for the request. This is where the session state module does it's work by reading the session cookie and finding the appropiate set of session variables for you.
AcquireRequestState runs before control is handed to your Page. So if you are calling other functionality, including static classes, from your page, you should be fine.
If you have some classes doing initialization logic during startup, for example on the Application_Start event or by using a static constructor, Session state might not be available. It all boils down to whether there is a current request and AcquireRequestState has been run.
Also, should the client have disabled cookies, the Session object will still be available - but on the next request, the user will return with a new empty Session. This is because the client is given a Session statebag if he does not have one already. If the client does not transport the session cookie, we have no way of identifying the client as the same, so he will be handed a new session again and again.
The following statement is not entirely accurate:
"So if you are calling other functionality, including static classes, from your page, you should be fine"
I am calling a static method that references the session through HttpContext.Current.Session and it is null. However, I am calling the method via a webservice method through ajax using jQuery.
As I found out here you can fix the problem with a simple attribute on the method, or use the web service session object:
There’s a trick though, in order to access the session state within a web method, you must enable the session state management like so:
[WebMethod(EnableSession = true)]
By specifying the EnableSession value, you will now have a managed session to play with. If you don’t specify this value, you will get a null Session object, and more than likely run into null reference exceptions whilst trying to access the session object.
Thanks to Matthew Cosier for the solution.
Just thought I'd add my two cents.
Ed
If your Session instance is null and your in an 'ashx' file, just implement the 'IRequiresSessionState' interface.
This interface doesn't have any members so you just need to add the interface name after the class declaration (C#):
public class MyAshxClass : IHttpHandler, IRequiresSessionState
In my case ASP.NET State Service was stopped. Changing the Startup type to Automatic and starting the service manually for the first time solved the issue.
ASP.NET Technical Articles
SUMMARY: In ASP.NET, every Web page
derives from the System.Web.UI.Page
class. The Page class aggregates an
instance of the HttpSession object for
session data. The Page class exposes
different events and methods for
customization. In particular, the
OnInit method is used to set the
initialize state of the Page object.
If the request does not have the
Session cookie, a new Session cookie
will be issued to the requester.
EDIT:
Session: A Concept for Beginners
SUMMARY: Session is created when user
sends a first request to the server
for any page in the web application,
the application creates the Session
and sends the Session ID back to the
user with the response and is stored
in the client machine as a small
cookie. So ideally the "machine that
has disabled the cookies, session
information will not be stored".

Resources