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原文地址

相关文章
相关标签/搜索