MojoDK
MojoDK

Reputation: 4528

Store javascript files in same folder as views in ASP.NET Core 1.1?

In an ASP.NET Web Application ... MVC (not core), I could in the web.config file add this...

<system.webServer>
    <handlers>
      <add name="JavaScriptHandler"
         path="*.js"
         verb="*"
         preCondition="integratedMode"
         type="System.Web.StaticFileHandler" />
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler"
           path="*"
           verb="*"
           preCondition="integratedMode"
           type="System.Web.HttpNotFoundHandler" />
    </handlers>
</system.webServer>

And then I could place a javascript file in same folder as the view files.

Can I somehow do the same in ASP.Net Core 1.1?

Thanks

Upvotes: 4

Views: 2054

Answers (1)

Ashley Lee
Ashley Lee

Reputation: 3986

Here is the official Microsoft documentation: Working with Static Files in ASP.NET Core

As part of the OWIN pipeline, no static files are rendered by default including those in the "wwwroot" folder. Where things used to be handled in web.config, now everything goes through the OWIN pipeline. You have to add the StaticFile Middleware which will allow those to be rendered. The default implementation allows all files under "wwwroot" to be rendered.

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles();
}

The documentation is provided in the link above for adding additional locations to allow files to be rendered from. It's not explicit, but you can look at the implementation of the StaticFile Middleware at Github to get ideas for custom implementations.

The below code will add StaticFiles Middleware to only allow javascript files to be rendered from the "Views" folder. You can add other files by adding items to the Dictionary.

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles();

    // Render only .js files in "Views" folder
    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"Views")),
            RequestPath = new PathString("/Views"),
            ContentTypeProvider = new FileExtensionContentTypeProvider(
                new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
                {
                    { ".js", "application/javascript" },
                })
        }
    );
}

Your only other alternative is to add custom grunt (or gulp) tasks to copy your javascript files in your "Views" folders into new folders created in your "wwwroot" folder. You can see some examples here of compiling TypeScript code and doing something similar. Using Grunt Tasks

Upvotes: 6

Related Questions