Asp.net

在 Web.Config 的 Location Path 元素中指定多個目錄

  • January 5, 2011

在我的 ASP.NET 的 Web Config 文件中,我定義了以下位置元素:

 <location path="">
   <system.web>
     <authorization>
       <deny users="?"/>
     </authorization>
   </system.web>
 </location>

 <location path="dir1">
   <system.web>
     <authorization>
       <allow users="?"/>
     </authorization>
   </system.web>
 </location>

 <location path="dir2">
   <system.web>
     <authorization>
       <allow users="?"/>
     </authorization>
   </system.web>
 </location>

上面的範例指定所有目錄將被鎖定給匿名使用者,除了兩個目錄 dir1 和 dir2。

我很好奇是否有一種我可以使用的語法允許我在一個位置元素中定義多個目錄。例如,如果我們可以做這樣的事情會很方便……

 <location path="dir1,dir2,etc">
   <system.web>
     <authorization>
       <allow users="?"/>
     </authorization>
   </system.web>
 </location>

對不起,但是路徑屬性不允許使用“,”所以你必須為所有路徑寫標籤,或者你可以在每個目錄中創建 web.config。

您不能在 path 屬性中指定多個元素,但可以使用 configSource 屬性。

例如,以下原始 web.config 文件:

<?xml version="1.0"?>
<configuration>
 <location path="form1.aspx">
   <system.web>
     <authorization>
       <allow users="*"/>
     </authorization>
   </system.web>
 </location>
 <location path="form2.aspx">
   <system.web>
     <authorization>
       <allow users="*"/>
     </authorization>
   </system.web>
 </location>
 <location path="form3.aspx">
   <system.web>
     <authorization>
       <allow users="*"/>
     </authorization>
   </system.web>
 </location>
 <location path="form4.aspx">
   <system.web>
     <authorization>
       <deny users="*"/>
     </authorization>
   </system.web>
 </location>
 <location path="form5.aspx">
   <system.web>
     <authorization>
       <deny users="*"/>
     </authorization>
   </system.web>
 </location>
 <location path="form6.aspx">
   <system.web>
     <authorization>
       <deny users="*"/>
     </authorization>
   </system.web>
 </location>
</configuration>

可以替換為以下等效的 web.config、allow.config 和 deny.config 文件:

網路配置

<?xml version="1.0"?>
<configuration>
 <location path="form1.aspx">
   <system.web>
     <authorization configSource="allow.config" />
   </system.web>
 </location>
 <location path="form2.aspx">
   <system.web>
     <authorization configSource="allow.config" />
   </system.web>
 </location>
 <location path="form3.aspx">
   <system.web>
     <authorization configSource="allow.config" />
   </system.web>
 </location>
 <location path="form4.aspx">
   <system.web>
     <authorization configSource="deny.config" />
   </system.web>
 </location>
 <location path="form5.aspx">
   <system.web>
     <authorization configSource="deny.config" />
   </system.web>
 </location>
 <location path="form6.aspx">
   <system.web>
     <authorization configSource="deny.config" />
   </system.web>
 </location>
</configuration>

允許配置

<?xml version="1.0"?>
<authorization>
 <allow users="*"/>
</authorization>

拒絕.config

<?xml version="1.0"?>
<authorization>
 <deny users="*"/>
</authorization>

這種方法的有用性隨著每個部分中允許/拒絕規則的數量增加而增加。

引用自:https://stackoverflow.com/questions/4608764