rogersillito rogersillito - 3 months ago 8
ASP.NET (C#) Question

Bundled css link gets a 404 error

I am trying to get bundling to work in ASP.NET MVC 4. I am getting a 404 error from the link generated for the bundled CSS. I have done the following:


  1. Installed the "Microsoft ASP.NET Web Optimization Framework" package via NuGet (v4.0.20710.0)

  2. Created a BundleConfig class in the App_Start dir with the following contents:

    using System.Web.Optimization;
    namespace BsdAppTemplate.Web_Nancy.App_Start
    {
    public class BundleConfig
    {
    public static void RegisterBundles(BundleCollection bundles)
    {
    bundles.Add(new StyleBundle("~/bundles/styles/cvi").Include(
    "~/mainstyles.css"
    ));
    }
    }
    }

  3. Added the following to Web.config at site root:

    <system.web>
    <compilation debug="false" targetFramework="4.5" />

    <pages>
    <namespaces>
    <add namespace="System.Web.Optimization"/>
    ...
    </namespaces>
    </pages>
    </system.web>

  4. Added the following to the head element of my MVC layout file:

    @Styles.Render("~/bundles/styles/cvi")

  5. Copied the CSS file referenced in BundleConfig ("mainstyles.css") into the root directory of my web project.



When I view the source of a rendered file, I can see the link appears as:

<link href="/bundles/styles/cvi" rel="stylesheet"/>


This link results in a 404 when browsing to it, or viewing the page request in Chrome's network tab.

I have also tried the equivalent on a web form, but I get the same result (404) from the link generated when I add:

<%: Styles.Render("~/bundles/styles/cvi") %>

Answer

It seems that you have missed the step in which you apply your configuration by calling RegisterBundles in Application_Start:

protected void Application_Start()
{
    ...
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    ...
}

Usually in cases where the BundleConfig class is already there (either as a part of the project template or created by NuGet package during the installation) this call is also already present - this is why many tutorials are implicit about it.

You should also be aware that the BundleConfig class is there for separation of concerns and in order to keep the Application_Start clean. In simple cases nothing prevents you from registering bundles directly in Application_Start:

protected void Application_Start()
{
    ...
    BundleTable.Bundles.Add(new StyleBundle("~/bundles/styles/cvi").Include("~/mainstyles.css"));

    ...
}