2012-12-26 49 views
2

有沒有一種簡單的方法來讀取web.config中cookieName爲anonymousIdentification節中信任工作時?Web.config anonymous通過Medium Trust中的代碼識別cookieName?

我試圖做的是防止數千名匿名用戶創建,因爲無論:

  1. 人關閉Cookie,或
  2. 訪問者是沒有的cookie功能的蜘蛛/機器人。

我是如何試圖完成這個是通過檢查Application_BeginRequest中的表單身份驗證或匿名身份cookie的存在。如果沒有cookie,我會設置一個標誌,以防止將任何內容保存到數據庫中。

但爲了做到這一點,我必須知道cookie的名稱。對於這一點,我試圖做到這一點:

AuthCookieName = FormsAuthentication.FormsCookieName; 
var anonSection = (AnonymousIdentificationSection)WebConfigurationManager.GetSection("system.web/anonymousIdentification"); 
if (anonSection != null) 
    AnonCookieName = anonSection.CookieName; 

雖然身份驗證cookie名稱是沒有任何問題檢索,該WebConfigurationManager拋出安全異常:System.Security.SecurityException:請求式「系統的權限。 Configuration.ConfigurationPermission,System.Configuration,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b03f5f7f11d50a3a'失敗。

我知道這是一個信任問題,因爲當我給高或完全信任之外消失。但是,在中等信任中這是很重要的,我不能修改machine.config。

有沒有一種方法來設置requirePermission="false"在我的anonymousIdentification部分應用程序的web.config水平?

上午我將不得不加載web.config中的XML文檔中,然後手動解析出來?

其他的想法?


有沒有比這更好的東西?我只在Application_Start()上跑過一次。

XmlDocument config = new XmlDocument(); 
config.Load(Server.MapPath("~/Web.config")); 
XmlNode anonSection = config.SelectSingleNode("configuration/system.web/anonymousIdentification"); 
if (anonSection != null) 
{ 
    XmlAttribute nameAttr = anonSection.Attributes["cookieName"]; 
    if (nameAttr != null) 
     AnonCookieName = nameAttr.Value; 
} 
if (string.IsNullOrWhiteSpace(AnonCookieName)) 
    AnonCookieName = ".ASPXANONYMOUS"; 
+0

「未經認證的用戶」可以保存到分貝?恕我直言,如果他們這樣做,我不明白爲什麼你需要區分(除非我失去了一些東西)。要查明用戶是否已通過身份驗證,不能['HttpRequest.IsAuthenticated'](http://msdn.microsoft.com/zh-cn/library/system.web.httprequest.isauthenticated.aspx)就足夠了嗎? – EdSF

+0

未經身份驗證的用戶數據也將保存到數據庫。 – Sam

+0

不會被簡化爲'HttpRequest.IsAuthenticated'(true或false)嗎? – EdSF

回答

0

據微軟稱,中信託已經死亡。但如果你必須這樣做,這應該工作:

XmlDocument config = new XmlDocument(); 
config.Load(Server.MapPath("~/Web.config")); 
XmlNode anonSection = config.SelectSingleNode("configuration/system.web/anonymousIdentification"); 
if (anonSection != null) 
{ 
    XmlAttribute nameAttr = anonSection.Attributes["cookieName"]; 
    if (nameAttr != null) 
     AnonCookieName = nameAttr.Value; 
} 
if (string.IsNullOrWhiteSpace(AnonCookieName)) 
    AnonCookieName = ".ASPXANONYMOUS";