ASP.NET MVC4中的bundles特性引起服務器拒絕訪問(403錯誤)

轉載: https://www.cnblogs.com/OpenCoder/p/5180325.htmljavascript

在ASP.NET MVC4中微軟引入了bundles特性,這個特性能夠將服務器端的多個Javascript或多個css文件捆綁在一塊兒做爲一個單一的URL地址供客戶端瀏覽器調用,從而減小了頁面上Http請求的訪問次數,增長頁面的響應速度。本文不打算介紹MVC4中的bundles特性,若是須要了解,推薦能夠查看下面這位博主的文章:css

在ASP.NET MVC中,使用Bundle來打包壓縮js和css html

 

本文要說的問題是當你使用bundles.Add方法添加StyleBundle和ScriptBundle對象的時候必定要注意,StyleBundle和ScriptBundle的構造函數的參數virtualPath指定的虛擬路徑必定不能是當前ASP.NET項目中真實存在的一個文件夾路徑,不然當你把你的站點部署到IIS上後,會發現MVC頁面上用@Styles.Render和@Scripts.Render生成的url路徑會被IIS拒絕,IIS提示 禁止訪問 403錯誤。java

 

下面是有個老外遇到了相同的問題,在StackOverFlow論壇上的提問:web

My MVC 4 application works fine on my local computer.瀏覽器

However, the CSS files are not working after I publish (are not affecting the layout of the website).服務器

I can see CSS the files are on the server.mvc

When I look at the source code, I can seeapp

<link href="/Content/css?v=fxCdHAOgPDvcROxkMfEwGQggO9uCfzckN3PaN8BOIzI1" rel="stylesheet"/>

where as on my local computer, the source code shows as函數

<link href="/Content/css/myFile.css" rel="stylesheet"/> <link href="/Content/css/myFile02.css" rel="stylesheet"/>

So, in the source code view on the server, I clicked on  Content/css?v=fxCdHAOgPDvcROxkMfEwGQggO9uCfzckN3PaN8BOIzI1 and the browser took me to a 403 - Forbidden: Access is denied.

I am adding the CSS files with the BunldeConfig.cs class

複製代碼
public class BundleConfig { // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/javascript").Include( "~/Scripts/1.9.1.js", "~/Scripts/jTools.js", "~/Scripts/script.js" )); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/Css/website.css", "~/Content/Css/banner.css", "~/Content/Css/reusable.css", "~/Content/Css/lists.css", "~/Content/Css/tooltip.css", "~/Content/Css/overlay.css" )); } }
複製代碼

My question is, assuming this isn't an IT issue with the server (it has been working fine until recently) is there something wrong with my code?

 

StackOverFlow論壇上專家的回答:

Your problem is that you are using ~/Content/css as a bundle alias in new StyleBundle("~/Content/css"), while this path actually exists.

So when you are requesting <link href="/Content/css?...> you are essentially asking for a directory listing and that is forbidden.

Try using something else, like new StyleBundle("~/Content/styles").

NOTE: If you do use something like ~/Content/styles as an alias you may have issues with relative urls in your .css files. It may seem odd, but you may better use something like ~/Content/Css/someAlias

 

也就是說構造StyleBundle和ScriptBundle時定義的虛擬路徑不能是服務器上真實存在的物理路徑,同時上面這位專家還提到StyleBundle的虛擬路徑最好也不要使用~/Content/styles,由於這可能會使.css文件的訪問出現問題,對於StyleBundle最好用~/Content/Css/someAlias來做爲虛擬路徑。

 

StackOverFlow原文地址

相關文章
相關標籤/搜索