ASP.NET MVC4中的bundles特性引发服务器拒绝访问(403错误)
转载: https://www.cnblogs.com/OpenCoder/p/5180325.html
在ASP.NET MVC4中微软引入了bundles特性,这个特性可以将服务器端的多个Javascript或多个css文件捆绑在一起作为一个单一的URL地址供客户端浏览器调用,从而减少了页面上Http请求的访问次数,增加页面的响应速度。本文不打算介绍MVC4中的bundles特性,如果需要了解,推荐可以查看下面这位博主的文章:
在ASP.NET MVC中,使用Bundle来打包压缩js和css
本文要说的问题是当你使用bundles.Add方法添加StyleBundle和ScriptBundle对象的时候一定要注意,StyleBundle和ScriptBundle的构造函数的参数virtualPath指定的虚拟路径一定不能是当前ASP.NET项目中真实存在的一个文件夹路径,否则当你把你的站点部署到IIS上后,会发现MVC页面上用@Styles.Render和@Scripts.Render生成的url路径会被IIS拒绝,IIS提示 禁止访问 403错误。
下面是有个老外遇到了相同的问题,在StackOverFlow论坛上的提问:
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.
When I look at the source code, I can see
<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来作为虚拟路径。