惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
GbyAI
GbyAI
G
Google Developers Blog
Engineering at Meta
Engineering at Meta
月光博客
月光博客
腾讯CDC
Recent Announcements
Recent Announcements
酷 壳 – CoolShell
酷 壳 – CoolShell
爱范儿
爱范儿
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
SegmentFault 最新的问题
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
阮一峰的网络日志
阮一峰的网络日志
博客园 - 【当耐特】
The GitHub Blog
The GitHub Blog
Last Week in AI
Last Week in AI
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News
Y
Y Combinator Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Martin Fowler
Martin Fowler
A
About on SuperTechFans
博客园 - 叶小钗

博客园 - wanna

不知是不是年纪大了,常想起博客园,博客堂的旧事.博客堂好像不再存在了,博客园经营的越红火了.还记得这些人,早期的大牛人? 希望新一年会是和平的一年 js类成员笔记 mssql keyword,statements Transact-SQL Optimization Tips ..from mssqlcity.com ASP.NET's Data Storage Objects 通过AOP提高代码的封装和可复用性 Tomcat 与 IIS 整合[转] 如果获取一个表列的最大值.. - wanna - 博客园 无法阻止的弹出窗口: - wanna - 博客园 Attribute C#的Random类的源码 Regex.cs C#的GUID是怎么样生成的 Ms的DateTime类源码 Ms的Calendar源码 MS的string.cs MS公开的gc.cs源码 MS公开的gchandle.cs源码
Create your own HttpContext class>> from 123aspx.net
wanna · 2006-02-10 · via 博客园 - wanna

Create your own HttpContext class

Introduction
 

Have you ever wanted to be able to retrieve information specific to your application from a component and/or class just like you can get to the common ASP.NET objects (Request, Response, etc...) through the HttpContext.Current static method? It's actually quite easy to accomplish. The easiest solution is to the use the HttpContext.Current.Items collection. However, a cleaner solution is to use the same concept as HttpContext.Current static method.

Let's begin by looking into why creating your own HttpContext.Current is cleaner then HttpContext.Current.Items collection. Occasionally, you might want to be able to access the current Page that you are in from a business component. Code #1 and Code #2 show how this could be possible utilizing the HttpContext.Items collection.

 
public class Home : System.Web.UI.Page
{
	public Home()
	{
		HttpContext.Current.Items.Add("ThePage",this);
	}
}

 
  Code #1  
 
public class BusinessComponent
{
    public static string BusinessMethod()
    {
	string returnData = null;
	Page page = null;

	if(HttpContext.Current!=null)
	{
		try
		{
			page = (Page) HttpContext.Current.Items["ThePage"];
		}
		catch
		{
			page = null;
		}
	}

	if((page!=null) && (page.IsValid))
	{
		returnData = "Business Method return value 1";
	}
	else
	{
		returnData = "Business Method return value 0";
	}

	return returnData;		
    }
}

 
  Code #2  

YourContext.Current.Page
 

Without going into the details of creating your own HttpContext.Current yet, let's assume you have already done this. Code #3 shows how you could access your Page object from YourContext.Current static method class.

 
public class BusinessComponent
{
	public static string BusinessMethod()
	{
		string returnData = null;
		Page page = YourContext.Current.Page;

		if((page!=null) && (page.IsValid))
		{
			returnData = "Business Method return value 1";
		}
		else
		{
			returnData = "Business Method return value 0";
		}

		return returnData;		
	}
}

 
  Code #3  

Comparing Code #3 to Code #2 you can see that to begin with there is less code. There is also no dependency of knowing the string key name of the page item in the collection. And furthermore you don't need to cast the generic object out of the Items collection into a Page class. And, IMHO, it feels better.

Creating the CoreContext.Current method
 

The first thing to do when creating your own HttpContext is to determine what are the items (Properties) you would like to expose in your Context object. Continuing with the Page example, let's start with a Page property. However, you probably would like to have a common base page class for all of your pages. Let's call this base page class CorePage and let's call the context class CoreContext. Code #4 shows the realization of this.

 
public class CoreContext
{
	private CorePage _CorePage=null;

	public CorePage CorePage
	{
		get { return _CorePage; }
	}

	internal void SetCorePage(CorePage corePage)
	{
		_CorePage = corePage;
	}
}


 
  Code #4  

Now, let's add the static method Current (code #5).

 
private const string CORE_CONTEXT_CALL_CONTEXT_KEY =
		 "BrianBilbro.BusinessCore.Web.CoreContext";

public static CoreContext Current
{
	get
	{
		return GetCoreContext();
	}
}

private static CoreContext GetCoreContext()
{
	CoreContext CoreContext=null;

	if(System.Runtime.Remoting.Messaging
.CallContext.GetData(CORE_CONTEXT_CALL_CONTEXT_KEY)!=null)
	{
		try
		{
	CoreContext = (CoreContext)	System.Runtime.Remoting.Messaging
		.CallContext.GetData(CORE_CONTEXT_CALL_CONTEXT_KEY);
		}
		catch
		{
			CoreContext = null;
		}
	}

	if(CoreContext==null)
	{
		CoreContext = new CoreContext();
		SetCoreContext(CoreContext);
	}

	return CoreContext;
}

private static void SetCoreContext(CoreContext CoreContext)
{
	System.Runtime.Remoting.Messaging.CallContext
.SetData(CORE_CONTEXT_CALL_CONTEXT_KEY,CoreContext);
}



 
  Code #5  

Code #5 reveals the secret of HttpContext.Current. Ok, ILDASM revealed the secret :) Thanks to Dolph Priest for showing me that. HttpContext.Current makes a call to System.Runtime.Remoting.Messaging.CallContext.GetData to retrieve the current HttpContext object for the thread. The same concept is used in CoreContext except it creates a new CoreContext if it doesn't exist in the CallContext.GetData collection. This guarantees that CoreContext.Current will always return a valid instance of CoreContext (i.e. it's never null).

And finally, code #6 shows the CorePage (the base Page). The CorePage sets a reference to itself in the CoreContext.Current class by call the CoreContext internal method SetCorePage.

 
public class CorePage : System.Web.UI.Page
{
	public CorePage()
	{
		SetCorePageToCoreContext();
	}

	protected void SetCorePageToCoreContext()
	{
		CoreContext.Current.SetCorePage(this);
	}
}



 
  Code #6  

Download
 

The full source to this article is provided in a Visual Studio.NET solution file containing two projects. The first project is the CoreContext and CorePage classes. The second project is a sample ASP.NET Web Application that uses CoreContext and CorePage.

Click Here To Download Article Source

Install Steps:

  1. Extract folders from zip file
  2. Copy (or move) BusinessCore folder to your wwwroot folder (e.g. c:\inetpub\wwwroot\businesscore)
  3. Open the BusinessCore project file BusinessCore.csproj with Visual Studio.NET
  4. From Visual Studio.NET select File->Add Project->Existing Project
  5. Navigate to the folder you unzipped in step #1 called BrianBilbro.BusinessCore.Web
  6. Select the project file BrianBilbro.BusinessCore.Web.csproj
  7. Save your solution file by selecting File->Save All from the Visual Studio main menu.
  8. You should be able to compile the project. Select Build->Build Solution
  9. Open your browser. Navigate to http://localhost/BusinessCore/Home.aspx to run the sample page.

Conclusion
 

The source in this article is presented only to demonstrate how you can create your own HttpContext.Current. In your CoreContext class you can make as many properties as you need available to your various components. I've used this concept to make a custom Session object available throughout my application. In another example, I made some specific business "states" available in the custom CoreContext class. Other business components were able to query the custom CoreContext for the current business state without having to pass the information around.