Подтвердить что ты не робот

Не удалось загрузить ресурс: 403 запрещено с .js Оптимизация

Я пытаюсь минимизировать мои .js и .css файлы.

Я установил упакованный Install-Package Microsoft.AspNet.Web.Optimization

Когда активна оптимизация с помощью BundleTable.EnableOptimizations = true;

Я получаю эту ошибку на клиенте:

Не удалось загрузить ресурс: сервер ответил со статусом 403 (Запрещено) http://localhost:22773/Content/themes/elevation/v=gnDLBbf1VVRuQDXtIYn1q0P3ICZG7oiwwgxPRbaLvqI1

У кого-нибудь есть представление о том, что я делаю неправильно?

--- Информация о BundleConfig -------------------------------

 public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        BundleTable.EnableOptimizations = true;

        bundles.Add(new ScriptBundle("~/bundles/myJquery").Include(

           "~/Scripts/jquery-1.9.1.js",
          "~/Scripts/jquery-ui-1.10.1.custom.js",
            "~/Scripts/jquery.signalR-1.0.1.js",
            "~/Scripts/signalr-hubs.js",
            "~/Scripts/Controls/Select/Simple/jquery.ui.selectmenu.js"
        ));


        bundles.Add(new ScriptBundle("~/bundles/shared").Include(
            "~/Scripts/global/prototypes.js",
            "~/Scripts/global/mathutil.js",
            "~/Scripts/global/elevationevents.js"
            ));


        bundles.Add(new ScriptBundle("~/bundles/core").Include(
            "~/Scripts/elevation/core/sys.config.js",
            "~/Scripts/elevation/core/bays.js",
            "~/Scripts/elevation/core/door.js",
            "~/Scripts/elevation/core/horiziontal.js",
            "~/Scripts/elevation/core/vertical.js"));


        bundles.Add(new StyleBundle("~/Content/themes/elevation").Include(
            "~/Content/themes/dialogs/dialogs.css",
            "~/Content/themes/social/ac/acSocial.css",
            "~/Content/themes/elevation/elevation.css"
      ));
    }
}

----------------------------- Я все еще не понял это ---------- -----------

Я использую 2013.net и iis8 на ОС Windows 7

Вот моя последняя ошибка, я не могу принять решение из режима отладки, потому что, если я это сделаю, я получу эту ошибку ниже.

    HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.

Most likely causes:
A default document is not configured for the requested URL, and directory browsing is not enabled on the server.

Things you can try:
If you do not want to enable directory browsing, ensure that a default document is configured and that the file exists.
Enable directory browsing.
Go to the IIS Express install directory.
Run appcmd set config /section:system.webServer/directoryBrowse /enabled:true to enable directory browsing at the server level.
Run appcmd set config ["SITE_NAME"] /section:system.webServer/directoryBrowse /enabled:true to enable directory browsing at the site level.
Verify that the configuration/system.webServer/[email protected] attribute is set to true in the site or application configuration file.

Detailed Error Information:
Module     DirectoryListingModule
Notification       ExecuteRequestHandler
Handler    StaticFile
Error Code     0x00000000
Requested URL      http://localhost:1499/Content/themes/elevation/?v=aukmuLTC3g_fDko3eWmzqq7A8miRqgsJKXA2GO3w-pg1
Physical Path      c:\users\administrator\documents\visual studio 2013\Projects\AlumCloud\AlumCloud\Content\themes\elevation\
Logon Method       Anonymous
Logon User     Anonymous
Request Tracing Directory      C:\Users\Administrator\Documents\IISExpress\TraceLogFiles\ALUMCLOUD(3)

More Information:
This error occurs when a document is not specified in the URL, no default document is specified for the Web site or application, and directory listing is not enabled for the Web site or application. This setting may be disabled on purpose to secure the contents of the server.
View more information »

Вот URL, который создается iis8, когда он не находится в режиме отладки, который вызывает ошибку

http://localhost:1499/Content/themes/elevation/?v=aukmuLTC3g_fDko3eWmzqq7A8miRqgsJKXA2GO3w-pg1

Вот URL, который возвращает фактический .css файл с любой ошибкой

http://localhost:1499/Content/themes/elevation/elevation.css
4b9b3361

Ответ 1

Просто такая же проблема. В моем случае решение заключалось в том, чтобы дать Content bundle другое имя. Я думаю, что это происходит потому, что IIS перехватывает запросы и обрабатывает имя пакета как каталог, и поскольку папка Content действительно существует, она возвращает запрещенную ошибку. Итак, вы можете переименовать ~/Content/themes/elevation, чтобы сказать ~/css/themes/elevation

bundles.Add(new StyleBundle("~/css/themes/elevation").Include(
            "~/Content/themes/dialogs/dialogs.css",
            "~/Content/themes/social/ac/acSocial.css",
            "~/Content/themes/elevation/elevation.css"
      ));

Кроме того, не забудьте настроить свою страницу разметки/главной страницы, чтобы использовать измененное имя пакета, т.е.

<%: Styles.Render("~/css/themes/elevation") %>

Затем добавьте директивы location в web.config, чтобы разрешить доступ к пакетам:

<location path="css">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
  <location path="bundles">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>

Надеюсь, что это поможет.

Ответ 2

вы должны сохранить имя пакета аналогичным фактическому пути ресурсов. иначе система не может найти ресурсы при компиляции с помощью debug='false' или BundleTable.EnableOptimizations = true;. потому что система использует имя пакета для создания ссылки для ресурсов. поэтому имена ваших пакетов должны быть такими:

bundles.Add(new ScriptBundle("~/Scripts/myJquery").Include(
    "~/Scripts/jquery-1.9.1.js",
    "~/Scripts/jquery-ui-1.10.1.custom.js",
    "~/Scripts/jquery.signalR-1.0.1.js",
    "~/Scripts/signalr-hubs.js",
    "~/Scripts/Controls/Select/Simple/jquery.ui.selectmenu.js"
));

bundles.Add(new ScriptBundle("~/Scripts/global/shared").Include(
    "~/Scripts/global/prototypes.js",
    "~/Scripts/global/mathutil.js",
    "~/Scripts/global/elevationevents.js"
));

bundles.Add(new ScriptBundle("~/Scripts/elevation/core/core").Include(
    "~/Scripts/elevation/core/sys.config.js",
    "~/Scripts/elevation/core/bays.js",
    "~/Scripts/elevation/core/door.js",
    "~/Scripts/elevation/core/horiziontal.js",
    "~/Scripts/elevation/core/vertical.js"
));

bundles.Add(new StyleBundle("~/Content/themes/dialogs/dialog").Include(
    "~/Content/themes/dialogs/dialogs.css"
));

bundles.Add(new StyleBundle("~/Content/themes/social/ac/ac").Include(
    "~/Content/themes/social/ac/acSocial.css"
));

Edit Это будет работать на IIS 6. Однако для IIS 7 или 7.5 решение - это нечто иное. Я столкнулся с той же проблемой, когда я применил приложение в IIS 7.5. Решение состоит в том, чтобы установить исправление, как описано в ASP.NET MVC 4 в IIS 7.5, возвращает 404. Что-то делать с отображением маршрутов без расширения и ASP.NET 4.5 MVC 4 не работает в Windows Server 2008 IIS 7

Ответ 3

Вы уверены, что это должно быть /elevation/v = gn... но not/themes/elevation? v = gnDLBbf (с ?)?

Ответ 4

Как уже упоминалось в принятом ответе, имя связки, которое вы назначили, сталкивается с фактической существующей папкой. В качестве примера рассмотрим следующее:

bundles.Add(new StyleBundle("~/content/epic").Include(
    "~/Content/Epic/StickyFooter.css"));

Дает мне тот же тип ошибок, отмеченный OP:

{myURL}/content/epic/?v=YTZL7Up6r-0uQblkv6unjKN5Nfb3uwtE0bPz9nxbjDc1 Failed to load 

Это связано с тем, что виртуальный путь, который пытается создать оптимизатор (content/epic), является существующим пути к папке на моем сайте (у меня есть папка в корневом каталоге, называемая "content", и она содержит папку под названием "эпос" ). Если я изменю свой путь к следующему:

bundles.Add(new StyleBundle("~/content/epic2").Include(
    "~/Content/Epic/StickyFooter.css"));

Проблема больше не существует, потому что у меня нет папки под названием "epic2" внутри моей папки "content".

В отличие от принятого ответа, я бы посоветовал не менять каталог пакетов, например "~/Content/a/b/", на "~/css/a/b", потому что есть еще одна потенциальная проблема, которая возникнет, если ваши таблицы стилей содержат относительные ссылки на внешние файлы.

Рассмотрим мою таблицу стилей AjaxLoadAnimation.css, которая содержит этот фрагмент:

...
background: rgba( 255, 255, 255, .5 ) url('images/spin.gif') 50% 50% no-repeat;
...

Чтобы убедиться, что ссылка работает для оптимизированной и не оптимизированной компиляции, убедитесь, что путь для пакета соответствует пути для каждого элемента в комплекте. Если ваши таблицы стилей находятся на пути ~/Content/my/, ваш пакет должен начинаться с ~/Content/my/path. Чтобы избежать проблемы с OP, просто убедитесь, что имя ( "sharedcss" в моем случае) не конфликтует с существующей папкой.

bundles.Add(new StyleBundle("~/Content/my/path/sharedcss").Include(
    "~/Content/my/path/bootstrap.css",
    "~/Content/my/path/font-awesome.css",
    "~/Content/my/path/AjaxLoadAnimation.css"));

Надеюсь, это спасет других людей от такого же разочарования.