[ASP.NET]重构Session确实让代码简洁干净了不少

简介:

CodeProject的这篇文章确实对我有所启迪,
http://www.codeproject.com/useritems/SessionWrapper.asp#xx1208856xx

诚如作者所说,我们经常在ASP.NET用许多类似于下面的代码来检测Session中存储的对象,来防止Session过期后存储的变量丢失问题:
Int32 nUserID = -1;
if ( null != Session["userID"] ) {
  if ( Session["userID"] is Int32 ) {
    if ( 0 < Session["userID"] ) {
      nUserID = (Int32) Session["userID"]
    }
  }
}
if ( -1 == nUserID )
{
  throw new ApplicationException ( "Unexpected situation: userID invalid." );
}

this.doSomething( nUserID );
这样的代码会遍布各处。

那么,利用他的这个封装方案来做重构,确实让代码简洁干净了不少!
经过他的封装,上面的代码用这么一句话就行了:

this.doSomething( CCurrentSession.UserID )

他的类其实也很简单,如下所示:

using  System;
using  System.Web;

///--------------------------------------------------------------------
/// Developed by M. van Eijkel - aug 2005 
/// [e]: marcelvaneijkel@gmail.com
/// [w]: www.vaneijkel.com


namespace  VanEijkel.Web
{
    
/// <summary>
    
/// Wrapper class for the session object.
    
/// It centralizes the logic for retrieving and validation of session information.
    
/// By using an approach like this you improve the protection and encapsulation of existing code.
    
/// It offers a simple, low-risk, easy manageable way to improve existing WebApplication.
    
/// Therfore, I call it webRefactoring.
    
/// </summary>

    public class CurrentSession
    
{
    
#region Constants
    
private const String sMANDATORY_SESSION_KEY_NOT_FOUND_MSG = "Session variable excepted but does not exist. Key={0}";
    
private const String sMANDATORY_SESSION_VALUE_INVALID_NULL = "None null session value excepted. Key={0}";

    
private const Int32 nUSERID_UNKOWN = -1;
    
private const Int32 nUSERID_MINIMUM = 1;
    
private const String sUSERID_INVALID = "Invalid UserID:{0}. UserID should be larger than:{1}";
    
#endregion


    
#region UserID
    
/// <summary>
    
/// Returns the userID as a Int32 instead of an object.
    
/// This way you will get the compiler protection and intelligence support you need.
    
/// </summary>

    public static Int32 UserID
    
{
      
get 
      
{
        
return (Int32) GetValueOrDefault( eKeys.UserID, nUSERID_UNKOWN );
      }

      
set
      
{
        
if ( nUSERID_MINIMUM >= value )
        
{
          
throw new ApplicationException ( String.Format(sUSERID_INVALID, value, nUSERID_MINIMUM ));
        }

        SetValue( eKeys.UserID, value );
      }

    }

    
#endregion


    
#region private: GetValueOrDefault( eKeys eKey, Object oDefaultValue )
    
/// <summary>
    
/// Gets the value from the session object.
    
/// </summary>
    
/// <param name="eKey"> The session key to get the value for.</param>
    
/// <param name="oDefaultValue">The default value to use if no valid value stored.</param>
    
/// <returns>When the value is null or the key does not exist, 
    
/// the specified default value is returned. 
    
/// Otherwise, the value is returned</returns>

    private static object GetValueOrDefault( eKeys eKey, Object oDefaultValue )
    
{
      
//get the value
      object oValue = GetValue( eKey );

      
//value not found or null?
      if (null == oValue)
      
{
        
//return default value
        return oDefaultValue;
      }


      
//everything oke: return session value
      return oValue;
    }

    
#endregion

    
#region private: GetMandatoryValue( eKeys eKey )
    
/// <summary>
    
/// Returns the session value for a session-key that must exist.
    
/// If the key does not exist an applicationException is thrown.
    
/// </summary>
    
/// <param name="eKey"> The session-key to return the session-value for. </param>
    
/// <returns> A none-null value.</returns>

    private static object GetMandatoryValue( eKeys eKey )
    
{
      
//get the value
      object oValue = GetValue( eKey );

      
//key not found or value null?
      if ( null == oValue )
      
{
        
//throw applicationException because its application logic error (none CLR)
        throw new ApplicationException ( String.Format( sMANDATORY_SESSION_KEY_NOT_FOUND_MSG, eKey.ToString() ));
      }


      
//everything oke: return value
      return oValue;
    }

    
#endregion

    
#region private: GetValue( eKeys eKey )
    
/// <summary>
    
/// Gets the session value from the specified key.
    
/// </summary>
    
/// <param name="eKey">The key to get the value from</param>
    
/// <returns>The session value for the specified session key.
    
/// If the key does not exist, null is returned.
    
/// </returns>

    private static object GetValue( eKeys eKey )
    
{
      
return HttpContext.Current.Items[ eKey.ToString() ];
    }

    
#endregion


    
#region private SetMandatoryValue( eKeys eKey, Object oValue )
    
private static void SetMandatoryValue( eKeys eKey, Object oValue )
    
{
      
if ( null == oValue ) 
      
{
        
throw new ApplicationException(  String.Format(sMANDATORY_SESSION_VALUE_INVALID_NULL, eKey.ToString() ) );
      }

    }

    
#endregion

    
#region private SetValue( eKeys eKey, Object oValue)
    
/// <summary>
    
/// Stores the specified session-value to the specified session-key.
    
/// </summary>
    
/// <param name="eKey">The key for the value to store in the session.</param>
    
/// <param name="oValue">The value to store in the session</param>

    private static void SetValue ( eKeys eKey, Object oValue)
    
{
      HttpContext.Current.Items[eKey.ToString()] 
= oValue;
    }

    
#endregion


    
/// <summary>
    
/// An enum for the 
    
/// </summary>

    private enum eKeys
    
{
      UserID
    }

    }

}

目录
相关文章
|
12月前
|
算法 Java 测试技术
使用 BenchmarkDotNet 对 .NET 代码进行性能基准测试
使用 BenchmarkDotNet 对 .NET 代码进行性能基准测试
285 13
|
开发框架 .NET PHP
ASP.NET Web Pages - 添加 Razor 代码
ASP.NET Web Pages 使用 Razor 标记添加服务器端代码,支持 C# 和 Visual Basic。Razor 语法简洁易学,类似于 ASP 和 PHP。例如,在网页中加入 `@DateTime.Now` 可以实时显示当前时间。
|
敏捷开发 缓存 中间件
.NET技术的高效开发模式,涵盖面向对象编程、良好架构设计及高效代码编写与管理三大关键要素
本文深入探讨了.NET技术的高效开发模式,涵盖面向对象编程、良好架构设计及高效代码编写与管理三大关键要素,并通过企业级应用和Web应用开发的实践案例,展示了如何在实际项目中应用这些模式,旨在为开发者提供有益的参考和指导。
127 3
|
安全 Java 网络安全
Android远程连接和登录FTPS服务代码(commons.net库)
Android远程连接和登录FTPS服务代码(commons.net库)
291 1
|
前端开发 JavaScript C#
CodeMaid:一款基于.NET开发的Visual Studio代码简化和整理实用插件
CodeMaid:一款基于.NET开发的Visual Studio代码简化和整理实用插件
302 0
【Azure Key Vault】.NET 代码如何访问中国区的Key Vault中的机密信息(Get/Set Secret)
【Azure Key Vault】.NET 代码如何访问中国区的Key Vault中的机密信息(Get/Set Secret)
128 3
|
Kubernetes 监控 Devops
【独家揭秘】.NET项目中的DevOps实践:从代码提交到生产部署,你不知道的那些事!
【8月更文挑战第28天】.NET 项目中的 DevOps 实践贯穿代码提交到生产部署全流程,涵盖健壮的源代码管理、GitFlow 工作流、持续集成与部署、容器化及监控日志记录。通过 Git、CI/CD 工具、Kubernetes 及日志框架的最佳实践应用,显著提升软件开发效率与质量。本文通过具体示例,助力开发者构建高效可靠的 DevOps 流程,确保项目成功交付。
278 0
|
XML 开发框架 .NET
.NET框架:软件开发领域的瑞士军刀,如何让初学者变身代码艺术家——从基础架构到独特优势,一篇不可错过的深度解读。
【8月更文挑战第28天】.NET框架是由微软推出的统一开发平台,支持多种编程语言,简化应用程序的开发与部署。其核心组件包括公共语言运行库(CLR)和类库(FCL)。CLR负责内存管理、线程管理和异常处理等任务,确保代码稳定运行;FCL则提供了丰富的类和接口,涵盖网络、数据访问、安全性等多个领域,提高开发效率。此外,.NET框架还支持跨语言互操作,允许开发者使用C#、VB.NET等语言编写代码并无缝集成。这一框架凭借其强大的功能和广泛的社区支持,已成为软件开发领域的重要工具,适合初学者深入学习以奠定职业生涯基础。
308 1
|
微服务 API Java
微服务架构大揭秘!Play Framework如何助力构建松耦合系统?一场技术革命即将上演!
【8月更文挑战第31天】互联网技术飞速发展,微服务架构成为企业级应用主流。微服务将单一应用拆分成多个小服务,通过轻量级通信机制交互。高性能Java Web框架Play Framework具备轻量级、易扩展特性,适合构建微服务。本文探讨使用Play Framework构建松耦合微服务系统的方法。Play采用响应式编程模型,支持模块化开发,提供丰富生态系统,便于快速构建功能完善的微服务。
207 0
|
SQL 开发框架 .NET
代码更简洁,开发更高效:从零开始使用Entity Framework Core与传统ADO.NET构建数据持久化层的比较
【8月更文挑战第31天】在.NET平台上开发数据驱动应用时,选择合适的ORM框架至关重要。本文通过对比传统的ADO.NET和现代的Entity Framework Core (EF Core),展示了如何从零开始构建数据持久化层。ADO.NET虽强大灵活,但需要大量手写代码;EF Core则简化了数据访问,支持LINQ查询,自动生成SQL命令,提升开发效率。从创建.NET Core项目、定义数据模型、配置`DbContext`到执行数据库操作,EF Core提供了一套流畅的API,使数据持久化层的构建变得简单直接。
274 0