Building .NET Core Basic Application With Static Files - Day Three

In the previous articles of this series, we discussed why .NET Core was introduced by Microsoft and what are the main advantages of it. Also, in the previous articles, we learned how to develop basic console applications using .NET Core Architecture. Now, in this article, we will discuss how to handle static files in .NET Core Architecture.

If you want to look at the previous articles of this series, please visit the links given below.

Static files

One of the main features of ASP.NET Core is that it can be as lean as you like. This means, you are responsible for what you’re going to put into the application, but it also means that you can make the application very simple and fast.

In fact, if you start your project from an empty ASP.NET Core web application template, the application will not be able to serve static files. If you want to do it, you have to add and configure a specific package. A common question is “Why doesn't it support static files by default if all websites need static files?" The truth is that not all the websites need to serve static files, especially on high-traffic applications. In this case, the static files should be hosted by a content delivery network (CDN). Moreover, your web application could be an API application that usually serves data using JSON or XML format instead of images, stylesheets, and JavaScript.

Configure static files

As you’ll see, most of the configurations are managed by middleware components available on NuGet. That’s also true in this case; you have to install a specific package and configure its middleware. The package to install is Microsoft.AspNetCore.StaticFiles. You can get it using the Package Manager. You are almost ready. The last but still important thing to know is that the wwwroot folder present in the root of your project will contain all the static files. So, if you want to serve a file called image1.jpg for the request http://localhost:5000/image1.jpg, you have to put it into the root of the wwwroot folder, not in the root of the project folder like you were doing with the previous version of ASP.NET.

Single page application

Another scenario where the static-file middleware components combined with ASP.NET Core application could be very useful is for a web app that is a single page application (SPA). The best way to describe the meaning of SPA is via Wikipedia's definition-

"A single-page application (SPA) is a web application or website that fits on a single webpage with the goal of providing a user experience similar to that of a desktop application."

Basically, most of the business logic is present on the client. The server doesn't need to render different Views; it just exposes the data to the client. This is available thanks to JavaScript (combined with modern frameworks like Angular, React, Aurelia) and a set of APIs (in our case, developed with ASP.NET MVC Core).

If there is no server-side rendering, the web server must return a static file when the root domain is called by the browser (http://www.mysite.com). To do that, you have to configure the default documents into the Configure method of your Startup class.

For demonstrating this, we first need to create a blank or empty project of .NET Core applications. For this, just open the Microsoft Visual Studio 2017 as below.

 

Now, select the available existing project template, like Empty Project, just like console application.

 

Now, it contains two files as mentioned below.
 
Program.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.AspNetCore.Hosting;  
  7.   
  8. namespace Prog2_Middleware  
  9. {  
  10.     public class Program  
  11.     {  
  12.         public static void Main(string[] args)  
  13.         {  
  14.             var host = new WebHostBuilder()  
  15.                 .UseKestrel()  
  16.                 .UseContentRoot(Directory.GetCurrentDirectory())  
  17.                 .UseIISIntegration()  
  18.                 .UseStartup<Startup>()  
  19.                 .UseApplicationInsights()  
  20.                 .Build();  
  21.   
  22.             host.Run();  
  23.         }  
  24.     }  
  25. }  
Startup.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Builder;  
  6. using Microsoft.AspNetCore.Hosting;  
  7. using Microsoft.AspNetCore.Http;  
  8. using Microsoft.Extensions.DependencyInjection;  
  9. using Microsoft.Extensions.Logging;  
  10.   
  11. namespace Prog2_Middleware  
  12. {  
  13.     public class Startup  
  14.     {  
  15.         // This method gets called by the runtime. Use this method to add services to the container.  
  16.         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940  
  17.         public void ConfigureServices(IServiceCollection services)  
  18.         {  
  19.         }  
  20.   
  21.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  22.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  23.         {  
  24.             loggerFactory.AddConsole();  
  25.   
  26.             if (env.IsDevelopment())  
  27.             {  
  28.                 app.UseDeveloperExceptionPage();  
  29.             }  
  30.   
  31.             app.UseDefaultFiles();  
  32.             app.UseStaticFiles();  
  33.   
  34.             app.Run(async (context) =>  
  35.             {  
  36.                 await context.Response.WriteAsync("Hello World! Welcome to .Net Core World");  
  37.             });  
  38.         }  
  39.     }  
  40. }  
 Run the app. The output result is shown below.

 

Now, for using static files, we need to add the Microsoft.AspNetCore.StaticFiles from NuGet Manager and install that extension within the projects.

 
Select the wwwroot folder within Solution Explorer, and add an HTML file named index.html within the folder. 
 
 

Index.html 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <title></title>  
  6. </head>  
  7. <body>  
  8.     <h1>Hello ASP.Net Core... </h1>  
  9. </body>  
  10. </html>  
Now, change the Startup.cs files code with the following.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Builder;  
  6. using Microsoft.AspNetCore.Hosting;  
  7. using Microsoft.AspNetCore.Http;  
  8. using Microsoft.Extensions.DependencyInjection;  
  9. using Microsoft.Extensions.Logging;  
  10.   
  11. namespace Prog2_Middleware  
  12. {  
  13.     public class Startup  
  14.     {  
  15.         // This method gets called by the runtime. Use this method to add services to the container.  
  16.         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940  
  17.         public void ConfigureServices(IServiceCollection services)  
  18.         {  
  19.         }  
  20.   
  21.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  22.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  23.         {  
  24.             loggerFactory.AddConsole();  
  25.   
  26.             if (env.IsDevelopment())  
  27.             {  
  28.                 app.UseDeveloperExceptionPage();  
  29.             }  
  30.   
  31.             app.UseDefaultFiles();  
  32.             app.UseStaticFiles();  
  33.   
  34.             app.Run(async (context) =>  
  35.             {  
  36.                 await context.Response.WriteAsync("Hello World! Welcome to .Net Core World");  
  37.             });  
  38.         }  
  39.     }  
  40. }   
Now, run the application. The output is shown below.

You can read the next part here,


Similar Articles