Adding CSS, JS & Fonts to Asp.net Core MVC

If you are done with adding MVC to asp.net core, you must have added your first controller and a corresponding razor view. Adding all the HTML code along with js and CSS files the developers expect to see a great looking page in the browser after compiling the solution. But to their surprise something like following appears

OutputWithoutCSS

Dont worry, nothing happened to your CSS or js files. Asp.net core has provided a middleware to handle the static files.

app.UseStaticFiles();

Adding this middleware to Asp.net core pipeline along with MVC middleware allows you to host your static files in a folder with the name “wwwroot”. This folder already exists in the solution when you created the project. Lets add “UseStaticFiles()” to our Startup class’ configuration method.

public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole();
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseStaticFiles();
    // Use MVC with default Route HomeController/Index
    app.UseMvcWithDefaultRoute();
}

Lets assume we have following directory structure.

WwwrootDirectory

following paths can be used to access the CSS or JS files

<!-- Bootstrap Core CSS -->;
				<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
				<link href="css/modern-business.css" rel="stylesheet">
<!-- Custom Fonts -->
				<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet"   type="text/css">

Nothing changes in the URL it’s just how you host the contents on the server-side and how Asp.net core knows about the static contents.

Changing Directory for Static Files

If by any chance you need to change the directory to host the static files e.g., a temp directory you can use the following optional arguments while adding the middleware.

Add following two namespaces in Startup.cs file.

using Microsoft.Extensions.FileProviders;
using System.IO;

Also add the following middleware to Startup.cs class.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseStaticFiles();
    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(
    Path.Combine(Directory.GetCurrentDirectory(), @"Temp")),
        RequestPath = new PathString("/Temp")
    });

    // Use MVC with default Route HomeController/Index
    app.UseMvcWithDefaultRoute();
}

Adding UseStaticFiles() with no arguments will allow the solution to host static files from wwwroot folder. UseStaticFiles() with StaticFileOptions as arguments allows to specify any folder where you can host the static files. RequestPath specify a path string that will be used to get the files from the Temp directory.

Control the Response of Static Files

Static file options accepts a named variable OnPrepareResponse which is an action that is called when the response is ready to be flushed on the stream. All the headers and status codes are set but the body is not written. Developers can make important decisions or add more necessary headers in the response e.g., cache headers or content type headers.

app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(
    Path.Combine(Directory.GetCurrentDirectory(), @"Temp")),
    RequestPath = new PathString("/Temp"),
    OnPrepareResponse = ctx => {
        ctx.Context.Response.Headers.Apend("Cache-Control", 
        "public,max-age=600");
    }
});

Having all of the middleware place, we can see the HTML working perfectly fine presenting content of the page beautifully.

OutputWithCSS

You can add up all the beautiful CSS frameworks and fonts with ease now and with better control using c#. No need to get back to the IIS for managing static contents and their delivery to the clients separately.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s