ASP.NET's Data Storage Objects

ASP.NET's Data Storage Objects

Introduction

In this brief tutorial, we'll look at five different ASP.NET objects we can use to store data. Two of these, the Application and Session objects, should be pretty familiar to anyone coming from ASP. The other three, Context, Cache and ViewState are brand new to ASP.NET. Each object is ideal under certain conditions, varying only in scope (that is the length of time data in them exists, and the visibility of the data), and it's a complete understanding of this variation that we are after. Also, most of these objects have alternatives that we'll briefly look at.

Scope

Since the only difference between all these objects is their scope, it's important to have a clear understanding of exactly what this means. Within the context of this discussion, scope refers to how data inside these objects (or the objects themselves) live for. For example, a user's user ID should exist until he or she logs out, but the new password he or she enters should only exist for the life of the individual request.

Scope also refers to the visibility of the data. There're only two types of visibility, data is either available throughout the entire application or for a specific user. An example of this would be the SMTP server name to use when sending an email which should be globally accessible, whereas an email address is specific to an individual user.

Commonality

The above objects all expose their data-storage capabilities via something similar to a HashTable.

In other words, getting or setting information into or out of any of them is very similar.

All can hold any object as a value, and while some can have an object as a key, some can only have a string - which is what you'll be using 98% of the time. For example:

//C#
//setting
Application.Add("smtpServer", "127.0.0.1");
Context.Items.Add("culture", new CultureInfo("en-CA"));
Session.Add("userId", 3);

//getting
string smtpServer = (string)Application["smtpServer"];
CultureInfo c = (CultureInfo)Context.Items["culture"];
int userId = (int)Session["userId"];

HTTPApplication

mvc里面可以通过以下代码,来获取全局的HttpApplication

HttpApplication application = HttpContext.Current.ApplicationInstance;

The Application object is an instance of the System.Web.HTTPApplication class. Typically you would set values in the Application object on the Application_Start event of the Global.Asax or the BeginRequest event of a HttpModule. Logical values to store would be the SMTP server to use when sending out emails, the administrator's contact email address, and any other value which you might globally need across all users/requests.

Worker Process Recycling and Web Farms

While it's correct to say that data stored in the Application exists as long as the website is up, it would be incorrect to simply leave it at that. Technically, the data in the Application exists as long as the worker process (the actual aspnet.exe if you will) exists. This can have severe repercussion令人不满意的后果 and isn't a mere仅仅的 technicality技术性细节. There are a number of reasons why the ASP.NET worker process recycles itself, from touching the web.config, to being idle空转, or consuming too much RAM. If you use the Application object by setting values to it in the Application_Start event and only read from it in your classes/pages, then no problem. When the worker process recycles itself, Application_Start will fire and your values will be properly set. However, if you set a value in the Application_Start event, update the value later on, when the worker process recycles itself, it'll default back to the Application_Start value.

Something else to keep in mind is that data stored in the Application object is specific to a computer and can't be (easily) shared across web farms.

Alternatives

The Application object might have been quite useful in Classic ASP, but a number of better alternatives (in my opinion) are now available.

Web.Config

If you require values that are readonly/constants (such as our SMTP server example), consider using the web.config. Unlike values in the Application, the web.config can be easily and quickly changed. You can do considerably advanced things in the web.config, check out my tutorial on Creating Custom Configurations.

Constants

You can leverage利用 the Object Oriented nature of ASP.NET and create a utility class with public constants. To be honest, unless you are just mocking something up, I'm not sure why you would ever use this method over using the web.config. It really gives you nothing except for headaches in the long run.

HttpCache + (XML | DB)

While custom sections in the web.config is definitely the way to go for read-only values, what can we do about read/write values and avoid worker process recycling? The answer is to store values in an XML file or database. While you could do the same thing in classic ASP, you can now leverage a new storage object, the HttpCache (which we'll cover next) to avoid any major performance penalty you would otherwise have. This also avoids any web farm issues you'd have with the HttpApplication class.

Conclusion

It is my opinion that the usefulness of the HttpApplication class, from a data storage point of view, is greatly diminished减少,缩小;变小 in ASP.NET. Powerful custom configuration sections in the web.config are a far more elegant and flexible solution for read-only values. Using XML files or a database is ideal for read/write values and web farms, and when combined with the HttpCache object leaves poor'ol Application in the dust.

HttpCache

The HttpCache (cache) class is the first new storage class we'll look at. It's also the most unique最独特的. There are a couple of reasons for this uniqueness. First, HttpCache isn't really a storage mechanism, it's mostly used as a proxy to a database or file to improve performance. Secondly, while you read values from the cache by specifying a key, you have a lot more control when inserting, such as how long to store the data, triggers to fire when the data is removed, and more. When accessing values from the cache, there's no guarantee that the data will be there (there are a number of reasons why ASP.NET would remove the data), as such, the typical way to use the cache is as follows:

private DataTable GetStates() {
   string cacheKey = "GetStates";  //the key to get/set our cache'd data

   DataTable dt = Cache[cacheKey] as DataTable;
   if(dt == null){

      dt = DataBaseProvider.GetStates();
      Cache.Insert(cacheKey, dt, null, DateTime.Now.AddHours(6), TimeSpan.Zero);
   }

   return dt;
}

First thing we do is declare a cacheKey [line: 2] which we'll use when retrieving and storing information from and into the cache.

Next, we use the key and try to get the value from the cache [line: 3]. If this is the first time we called this method, or if the data has been dropped for whatever reason, we'll get null/Nothing [line: 4]. If we do get null/Nothing, we hit the database via the fictional DataBaseProvider.GetStates() call [line: 5] and insert the value into the Cache object with our cacheKey [line: 6]. When inserting, we specify no file dependencies and we want the cache to expire in six hours from now.

The important thing to note about the code above is that the processing-heavy data-access code DataBaseProvider.GetStates() is skipped when we find the data in the cache. In this example, the real storage mechanism is a fictional虚构的 database; HttpCache simply acts as a proxy. It's more likely that you'll want to retrieve information based on parameters, say all the states/provinces for a specific country, this is easily achieved via the VB.NET code below:

 All I really had to do was add the parameter to my cacheKey, which means if I first try and get the states for country 3, my cacheKey will look like GetStates:3 and I'll need to hit the database. Subsequent requests for GetStates:3 will avoid the DB call. However, when I ask for states of country 2, my cacheKey looks like GetStates:2, which, when first called will hit the DB, and subsequently retrieve the right values.

SessionState

Sessions exist for the lifetime of a specific user's visit, or until the session timeouts, or you remove it. One thing you probably heard a lot in your ASP days was "don't use sessions", or "sessions are evil". The problem with sessions is how easy they were to use combined with their potentially serious impact on performance, since they were stored in memory. In ASP.NET, you have the choice of storing sessions in memory, in a special service that is part of ASP.NET, or in a SQL database. Having this choice, and using it wisely, makes using sessions in ASP.NET a good thing.

You control where sessions are stored via the web.config's sessionState element, specifically the mode attribute:

<system.web>
   <!--<span class="code-comment"> can use a mode of "Off", "InProc", "StateServer" or "SQLServer". 
                                            These are CaSe-SeNsItIvE --></span>
    <sessionState mode="InProc" />
   ...
 </system.web>

InProc

InProc means that sessions are stored inside the ASP.NET worker process - this is pretty much how sessions in classic ASP work. Storing data this way can lead to performance issues (since it's using your web server's RAM), and also has all the issues associated with worker process recycling that plagues 使折磨,使苦恼;纠缠,缠扰;使得灾祸 read/write usage of the Application object. However, wisely used for the right website, such as keeping track of a user ID in a small/medium sized site, they are extremely performing and an ideal solution. You don't need to do anything special, other than setting the sessionState's mode to "InProc".

StateServer

StateServer is a service which is off by default. You can enable it by going into "Administration" --> "Services" and right-clicking on "ASP.NET State Service" (go to Properties and select "automatic" if you want it to start when Windows starts). When your sessionState is in StateServer, sessions aren't stored in the ASP.NET worker-process, which avoids the worker process recycle problem. Additionally, two or more separate web servers can access a single StateServer, meaning session state will automatically be shared across a web farm.

There are two very important things to keep in mind when using StateServer.

Firstly, it isn't as fast as having the data stored directly in the ASP.NET worker process. This can be easily resolved by smarty using the HttpCache class.

Secondly, data stored in the StateServer must be serializable. Strings, ints and most built-in types are mostly all automatically serializable. Custom classes can typically be marked by the System.SerializableAttribute attribute:

[Serializable()]
public class User {
   private int userId;
   private string userName;
   private UserStatus status;

   public int UserId {get { return userId; } set { userId = value; }}
   public string UserName {get { return userName; }set { userName = value; }}
   public UserStatus Status {get { return status; }set { status = value; }}

   public enum UserStatus {
      Invalid = 0,
      Valid = 1
   }
}

To use StateServer, you must specify both the SessionState mode, as well as the address of the StateServer via stateConnectionString. StateServer runs on port 42424 by default, so the example below connects to the state server on the local machine.

<sessionState mode="StateServer" 

       stateConnectionString="tcpip=127.0.0.1:42424" />

SQL Server

Using SQL Server is much like using StateServer. Both require data to be serializable, both are overall slower (but won't cause the entire app to have performance issues), and both can be accessed by multiple web servers. The difference between the two is, well obviously, one uses the StateServer service while the other uses SQL Server. This has pretty wide implications含义;暗示;牵连,卷入;可能的结果,影响. By storing your sessions in SQL Server, you can take advantage of multiple databases, load balancing, and fault-tolerance. You also have to pay big money for it.

Enabling SQL Server is much like StateServer: set the mode to SQLServer and specify the connection via the sqlConnectionString attribute:

<sessionState mode="SQLServer" 

   stateConnectionString="Initial Catalog=Session;server=localhsot;uid=sa;pwd=;" />

Additionally, you must run a script to create the database. This script is located in system driveWINNTMicrosoft.NETFrameworkversionInstallSqlState.sql, for example: C:WINDOWSMicrosoft.NETFrameworkv1.1.4322InstallSqlState.sql on my computer (Windows instead of WinNT because I'm using XP). Simply run it, and you're ready to go.

C:WindowsMicrosoft.NETFramework64v4.0.30319InstallSqlState.sql

Alternatives

Considering how flexible and powerful sessions are now implemented, there aren't any great alternatives, but here's a list anyways:

Cookies

Cookies behave pretty much the same as sessions, but are stored on the user's computer. This makes them horrible可怕的 for large data or sensitive information. Additionally, not everyone has cookies enabled (truer and truer with increased privacy concerns). On the flip side, unlike sessions, you can easily use cookies to store information across multiple visits. Cookies used to be a great place to store information you didn't really care if it was kept or not, like a username (hey, if it's there great, the user has one less thing to type. If not, oh well), but most browsers do a better job of this than you can with cookies.

Querystring

The querystring used to be considered a possible alternative to sessions. But again, you can't store large/complex data in them or sensitive information. Additionally, it's a real maintenance nightmare.

URL Rewriting

I won't go into details about URL Rewriting (check out my Localization Tutorial where I explain it briefly). I like using URL Rewriting for simple things such as localization because it needs far less maintenance than using the Querystring, and looks really professional. But just like the cookie or querystring alternative, this won't cut it most of the time.

Conclusion

As you can probably tell, sessions in ASP.NET are a lot more useful than they were in classic ASP. The main reason being that you have a good alternative to storing them in memory. But with that comes a bunch of other alternatives: sharing them across web farms (state server/ SQL Server), load balancing (SQL Server), fault tolerance (SQL Server), and a couple of other nice things. Another great feature of sessions in ASP.NET is that they'll work even if the user's browser doesn't support session cookies. This is done by automatically placing the session ID in the querystring, instead of a session cookie. Sure, I just said the QueryString was a bad alternative, but this is automatically done, maintenance free for us!

ViewState

You've probably heard a lot about viewstate and ASP.NET. It's one of the many big-things in ASP.NET. Thankfully (or not depending on how you look at it), I don't plan on going into any details about it, aside for how you can use it as a storage mechanism. For all its glory光荣,荣誉;赞颂, the ViewState is a hidden form field. You probably used hidden form fields frequently in classic ASP to track a value between one page and the posted-to page...our usage of the ViewState is no different. Its scope, as you can probably imagine, is for a single user, from one page to another.

What some people don't realize about the viewstate is that it isn't some mystical thing that they aren't allowed to touch. You can easily store and retrieve values from and into it:

原文地址:https://www.cnblogs.com/chucklu/p/13182020.html