javascriptasp.netangularjsasp.net-mvcasp.net-bundling

Cannot access JavaScript files inside View folder in ASP.NET MVC


I am trying to add AngularJS in my mvc project.

This is my bundle config

  public static void RegisterBundles(BundleCollection bundles) {

           bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/angularjs").Include(
                       "~/Scripts/angular.js",
                        "~/Scripts/angular-ui-router.js"));

               bundles.Add(new ScriptBundle("~/bundles/appscripts").Include(
                   "~/Areas/app.module.js",
                   "~/Areas/app.component.js",
                   "~/Areas/app.routes.js",

     bundles.Add(new ScriptBundle("~/bundles/appcomponents").Include(
      "~/Areas/Home/Views/Default/default.component.js"));
        }

_Layout.cshtml

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/angularjs")
    @Scripts.Render("~/bundles/appscripts")
    @Scripts.Render("~/bundles/appcomponents")
    @RenderSection("scripts", required: false)

I am able to add ~/bundles/jquery, ~/bundles/angularjs and ~/bundles/appscripts

enter image description here

but I am unable to add ~/bundles/appcomponents and I am getting a 404 error for this script.

enter image description here

I also tried adding the script file directly in the _layout.cshtml

<script src="~/Areas/Home/Views/Default/default.component.js"></script>

and I am getting the same error.

I am not sure why I am not able to add any scripts from the Views folder.

Can anyone please let me know how I can add this script file in the bundle config?


Solution

  • Due to security reason, web.config inside View folder blocks accessing files from browser. However, you can configure it to allow -

    <?xml version="1.0"?>
    
    <configuration>
      <configSections>
      ...        
      <system.webServer>
        <handlers>
          <remove name="BlockViewHandler"/>
          <add name="BlockViewHandler" path="*.js" verb="*" 
              preCondition="integratedMode" 
              type="System.Web.HttpNotFoundHandler" />
        </handlers>
      </system.webServer>
       ...
    </configuration>
    

    enter image description here

    Here is my answer similar to this question, but it is about cshtml file.