Just about every ASP.NET application needs to keep track of data for a users session. ASP.NET provides the HttpSessionState class to store session-state values. An instance of the HttpSessionState class for each HTTP request is accessible throughout your application using the static HttpContext.Current.Session property. Access to the same instance is made simpler on every Page and UserControl using the Session property of the Page or UserControl. The HttpSessionState class provides a collection of key/value pairs, where the keys are of type String and the values are of type Object. This means that Session is extremely flexible and you can store just about any type of data in Session. But (there is always a but) this flexibility does not come without a cost. The cost is the ease with which bugs can be introduced into your application. Many of the bugs that can be introduced will not be found by unit testing, and probably not by any form of structured testing. These bugs often only surface when the application has been deployed to the production environment. When they do surface it is often very difficult, if not impossible, to determine how they occured and be able to reproduce the bug. This means they are very expensive to fix. This article presents a strategy to help prevent this type of bug. It uses a Design Pattern called a Facade, in that it wraps the very free interface provided by the HttpSessionState class (that can meet the requirements of any application) with a well designed and controlled interface that is purpose built for a specific application. If you are not familiar with Design Patterns or the Facade pattern, a quick internet search of “facade design pattern” will provide you with plenty of background. However, you do not have to understand design patterns in order to understand this article. The example code shown in this article is written in C#, but the concepts are applicable to any .NET language. What is the problem? The following shows the typical code written to access session-state variables. // Save a session variable Using String Literals as Keys Session[“received”] = 27;… Most bugs like this will be identified by unit testing – but not always. It may not always be apparent that the value has not changed as expected. We can avoid this kind of bug by using constants: private const string received = “received”;… Consider the following code: Session[“maxValue”] = 27;… Session[“maxValue”] = 56.7; Most bugs like this will be identified by unit testing – but not always. Re-using a Key Unintentionally Code on one page: private const string edit = “edit”;… private const string edit = “edit”;… private const string edit = “edit”;… Usually this bug will NOT be picked up in testing. It is only when a user does some particular combination of page navigation (or opening a new browser window) that the bug manifests. At its worst, no one is aware that the bug has manifested, we may just end up modifying data to an unintended value. Re-using a Key Unintentionally – again Code on one page: Session[“FollowUp”] = “true”; Session[“FollowUp”] = 1; Session[“FollowUp”] = true; Usually this bug will NOT be picked up in testing. It is only when a user does some particular combination of page navigation (or opening a new browser window) that the bug manifests. What Can We Do? private const string limit = “limit”;… A Better Quick Fix public static class SessionKeys … Session[SessionKeys.Limit] = 27; However, we are still not ensuring consistency of data type. A Much Better Way – Using a Facade All session variables will be exposed as properties of the facade class. This has the same advantages as using a single class for all the session keys, plus the following advantages: Strong typing of what gets put into session variables. Collapse # region Public Properties // Check whether the UserAuthorisation has expired return userAuth; private set /// <summary> set /// <summary> set /// <summary> set The property getter for the UserAuthorisation property provides a simple cache of the UserAuthorisation class instance, ensuring that the instance in the session variables is kept up to date. This property also shows the use of a private setter, so that the value in the session variable can only be set under the control of facade class. The Username property demonstrates a value that may once have been stored as a session variable but is no longer stored this way. The following code shows how a session variable can be accessed through the facade. Note that there is not need to do any casting in this code. // Save a session variable Summary
In this section of the article I will describe the problems with direct access to the HttpSessionState class, without the facade. I will describe the kinds of bugs that can be introduced.
Session[“some string”] = anyOldObject;
// Read a session variable
DateTime startDate = (DateTime)Session[“StartDate”];
The problems arise from the flexibile interface provided by HttpSessionState: the keys are just strings and the values are not strongly typed.
If string literals are used as the keys, the string value of the key is not checked by the compiler. It is easy to create new session values by simple typing errors.
Session[“recieved”] = 32;
In the code above, two separate session values have been saved.
Session[received] = 27;…
Session[received] = 32;
No Type Checking
There is no type checking of the values being stored in session variables. The compiler cannot check correctness of what is being stored.
int maxValue = (int)Session[“maxValue”];
Elsewhere the following code is used to update the value.
If the code to read the “maxValue” session variable into the maxValue int variable is executed again there will be an InvalidCastException thrown.
Even when we define constants on each page for the session keys, it is possible to unintentionally use the same key across pages. Consider the following example:
Session[edit] = true;
Code on a second page, displayed after the first page:
if ((bool)Session[edit])
{
…
}
Code on a third, unrelated, page:
Session[edit] = false;
If the third page is displayed for some reason before the second page is displayed, the value may not be what was expected. The code will probably strill run, but the results will be wrong.
In the example above, the same data type was stored in the session variable. Because there is no type checking of what gets stored, the problem of incompatible data types can also occur.
Code on a second page:
Code on a third page:
When the bug manifests there will be an InvalidCastException thrown.
The First Quick Fix
The first and most simple thing we can do is make sure we never use string literals for session keys. Always use constants and so avoid simple typing mistakes.
Session[limit] = 27;…
Session[limit] = 32;
However, when constants are defined locally (e.g. at page level) we might still re-use the same key unintentionally.
Rather than define constants on each page, group all session key constants into a single location and provide documentation that will appear in Intellisense. The documentation should clearly indicate what the session variable is used for. For example, define a class just for the session keys:
{
/// <summary>
/// The maximum …
/// </summary>
public const string Limit = “limit”;
}
When you need a new session variable, if you choose a name that has already been used you will know this when you add the constant to the SessionKeys class. You can see how it is currently being used and can determine if you should be using a different key.
Only access the HttpSessionState from within one single static class in your application – the facade. There must be no direct access to the Session property from within code on pages or controls, and no direct access to HttpContext.Current.Session other than from within the facade
No need for casting in code where session variables are used.
All the benefits of property setters to validate what gets put into session variables (more than just type).
All the benefits of property getters when accessing session variables. For example, initialising a variable the first time it is accessed.
An Example Session Facade Class
Here is an example class to implement the Session facade for an application called MyApplication.
/// <summary>
/// MyApplicationSession provides a facade to the ASP.NET Session object.
/// All access to Session variables must be through this class.
/// </summary>
public static class MyApplicationSession
{
# region Private Constants
//———————————————————————
private const string userAuthorisation = “UserAuthorisation”;
private const string teamManagementState = “TeamManagementState”;
private const string startDate = “StartDate”;
private const string endDate = “EndDate”;
//———————————————————————
# endregion
//———————————————————————
/// <summary>
/// The Username is the domain name and username of the current user.
/// </summary>
public static string Username
{
get { return HttpContext.Current.User.Identity.Name; }
}
/// <summary>
/// UserAuthorisation contains the authorisation information for
/// the current user.
/// </summary>
public static UserAuthorisation UserAuthorisation
{
get
{
UserAuthorisation userAuth
= (UserAuthorisation)HttpContext.Current.Session[userAuthorisation];
if (
userAuth == null ||
(userAuth.Created.AddMinutes(
MyApplication.Settings.Caching.AuthorisationCache.CacheExpiryMinutes))
< DateTime.Now
)
{
userAuth = UserAuthorisation.GetUserAuthorisation(Username);
UserAuthorisation = userAuth;
}
}
{
HttpContext.Current.Session[userAuthorisation] = value;
}
}
/// TeamManagementState is used to store the current state of the
/// TeamManagement.aspx page.
/// </summary>
public static TeamManagementState TeamManagementState
{
get
{
return (TeamManagementState)HttpContext.Current.Session[teamManagementState];
}
{
HttpContext.Current.Session[teamManagementState] = value;
}
}
/// StartDate is the earliest date used to filter records.
/// </summary>
public static DateTime StartDate
{
get
{
if (HttpContext.Current.Session[startDate] == null)
return DateTime.MinValue;
else
return (DateTime)HttpContext.Current.Session[startDate];
}
{
HttpContext.Current.Session[startDate] = value;
}
}
/// EndDate is the latest date used to filter records.
/// </summary>
public static DateTime EndDate
{
get
{
if (HttpContext.Current.Session[endDate] == null)
return DateTime.MaxValue;
else
return (DateTime)HttpContext.Current.Session[endDate];
}
{
HttpContext.Current.Session[endDate] = value;
}
}
//———————————————————————
# endregion
}
The class demonstrates the use of property getters that can provide default values if a value has not been explicitly stored. For example, the StartDate property provides DateTime.MinValue as a default.
MyApplicationSession.StartDate = DateTime.Today.AddDays(-1);
// Read a session variable
DateTime startDate = MyApplicationSession.StartDate;
Additional Benefits
An additional benefit of the facade design pattern is that it hides the internal implemention from the rest of the application. Perhaps in the future you may decide to use another mechanism of implementing session-state, other than the built-in ASP.NET HttpSessionState class. You only need to change the internals of the facade – you do not need to change anything else in the rest of the application.
The use of a facade for HttpSessionState provides a much more robust way to access session variables. This is a very simple technique to implement, but with great benefit.
asp.net 2.0中的输出缓存_asp.net技巧
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » asp.net 2.0中的输出缓存_asp.net技巧
相关推荐
-      对.net framework 反射的反思_asp.net技巧
-      .net3.5和vs2008中的asp.net ajax_asp.net技巧
-      使用asp.net ajax框架扩展html map控件_asp.net技巧
-      asp.net应用程序资源访问安全模型_asp.net技巧
-      photoshop初学者轻松绘制螺旋漩涡特效_photoshop教程
-      photoshop通道结合图层模式抠狗尾巴草_photoshop教程
-      web.config详解+asp.net优化_asp.net技巧
-      asp.net中多彩下拉框的实现_asp.net技巧