既然你已經存儲HttpContext.User屬性的對象的所有你真的需要acheive你的目標是acheives你的目標一個靜態方法: -
public static class MySpecialContext
{
public static CommunityPrinciple Community
{
get
{
return (CommunityPrinciple)HttpContext.Current.User;
}
}
}
現在你可以得到CommunityPrinciple如下: -
var x = MySpecialContext.Community;
但是它似乎是一個很大的努力,要避免過分: -
var x = (CommunityPrinciple)Context.User;
另一種方法是對HttpContext的擴展方法: -
public static class HttpContextExtensions
{
public static CommunityPrinciple GetCommunity(this HttpContext o)
{
return (CommunityPrinciple)o.User;
}
}
使用它: -
var x = Context.GetCommunity();
這是相當整潔,但需要你記住要包括命名空間的擴展類的定義,其中在每個文件的使用列表中都需要它。
編輯:
讓我們假設對你有一些非常好的理由,甚至擔綱演出中稱爲上面的代碼的那一刻仍然是不可接受的(順便說一句,我會非常有興趣瞭解什麼情況引導你得出這個結論)。
又一替代方案是ThreadStatic字段: -
public class MyModule : IHttpModule
{
[ThreadStatic]
private static CommunityPrinciple _threadCommunity;
public static CommunityPrinciple Community
{
get
{
return _threadCommunity;
}
}
// Place here your original module code but instead of (or as well as) assigning
// the Context.User store in _threadCommunity.
// Also at the appropriate point in the request lifecyle null the _threadCommunity
}
甲場與[ThreadStatic]裝飾將具有每個線程的存儲的一個實例。因此,多個線程可以修改和讀取_threadCommunity,但每個線程都將在其特定的實例上運行。
感謝您的回覆。 這也是一個好主意。我通常會在控制器或視圖中使用它所以我可以創建一個自定義視圖和自定義控制器,我可以繼承。謝謝。 – MartinF 2009-10-13 15:19:10