Using Static Files (HTML, JavaScript) In Web API

In this article, we will see how to add static files or groups of static files to an existing ASP.Net Core web API project. As we all know the API project only deals with APIs. let's assume that you want to add a couple of static files to show data or showing some sort of configuration. At the beginning of the application if we can do that by choosing the web-based Template instead of the API template after the application has been created will have to use middleware to do that. By this article will have a clear picture of how we can achieve that after an application is already been created.
 
Source Code - Git Hub Repo
 

Agenda 

  • What are static files
  • Where should we place these static files 
  • How should we use these static files in the project

What are static files?

 
In the modern world, any web app must contain the below files for the look and feel of the project or as per the project requirement. To use these files inside the .Net project here are the simple steps to use these files inside the API Project.
  • Images
  • Html files
  • CSS files
  • javascript files 

Where should we place these static files

 
We can place the static files anywhere inside the project solution. In order to place those, we just need to create a new project for this demo. Create a sample Web API project with .Net Core 3.1 or .Net Core 5.0 Template after creating the project create a folder named StaticFiles where we will add our static files. Create an HTML file, Javascript file and CSS File inside the StaticFiles and folder looks like below.
 
 
 
Let's add the respective content in those Html files. To make it simple I had just added the static content to show how we are consuming these files. Later we test the file in the browser itself.
 
index.html
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <title></title>  
  6.     <script src="main.js"></script>  
  7.     <link href="main.css" rel="stylesheet" />  
  8. </head>  
  9. <body>  
  10.     <div>  
  11.         <h2>Hi,This is Jay<span>👋🏻</span></h2>  
  12.         <p>  
  13.             This article is all about how to serve static files using ASP.Net Core 5.0 Web API.  
  14.             Below is the Git hub URL to clone and play around with it.  
  15.             <a target="_blank" href="https://github.com/JayKrishnareddy/StaticFiles">"Static Files Web API"</a> link.  
  16.         </p>  
  17.     </div>  
  18.     <img src="AspnetCore.png" />  
  19. </body>  
  20. </html>  
main.css
  1. h2 {  
  2.     text-align: center;  
  3.     color: blue;  
  4. }  
  5. div {  
  6.     border: 1px solid gray;  
  7.     padding: 8px;  
  8. }  
  9. p {  
  10.     text-indent: 80px;  
  11.     text-align: justify;  
  12.     letter-spacing: 3px;  
  13. }  
main.js
  1. alert("Triggered URL");  
Now register the static files setup inside the Startup. cs file to make these files work when the actual API URL is triggered by using FileServer inside the Configure method.
  
Startup.cs 
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.AspNetCore.HttpsPolicy;  
  4. using Microsoft.AspNetCore.Mvc;  
  5. using Microsoft.Extensions.Configuration;  
  6. using Microsoft.Extensions.DependencyInjection;  
  7. using Microsoft.Extensions.FileProviders;  
  8. using Microsoft.Extensions.Hosting;  
  9. using Microsoft.Extensions.Logging;  
  10. using Microsoft.OpenApi.Models;  
  11. using System;  
  12. using System.Collections.Generic;  
  13. using System.IO;  
  14. using System.Linq;  
  15. using System.Threading.Tasks;  
  16.   
  17. namespace StaticFiles  
  18. {  
  19.     public class Startup  
  20.     {  
  21.         public Startup(IConfiguration configuration)  
  22.         {  
  23.             Configuration = configuration;  
  24.         }  
  25.   
  26.         public IConfiguration Configuration { get; }  
  27.   
  28.         // This method gets called by the runtime. Use this method to add services to the container.  
  29.         public void ConfigureServices(IServiceCollection services)  
  30.         {  
  31.   
  32.             services.AddControllers();  
  33.             services.AddSwaggerGen(c =>  
  34.             {  
  35.                 c.SwaggerDoc("v1"new OpenApiInfo { Title = "StaticFiles", Version = "v1" });  
  36.             });  
  37.         }  
  38.   
  39.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  40.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  41.         {  
  42.             if (env.IsDevelopment())  
  43.             {  
  44.                 app.UseDeveloperExceptionPage();  
  45.                 app.UseSwagger();  
  46.                 app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json""StaticFiles v1"));  
  47.             }  
  48.             app.UseFileServer(new FileServerOptions  
  49.             {  
  50.                 FileProvider = new PhysicalFileProvider(  
  51.                     Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),  
  52.                 RequestPath = "/StaticFiles",  
  53.                 EnableDefaultFiles = true  
  54.             }) ;  
  55.             app.UseHttpsRedirection();  
  56.   
  57.             app.UseRouting();  
  58.   
  59.             app.UseAuthorization();  
  60.   
  61.             app.UseEndpoints(endpoints =>  
  62.             {  
  63.                 endpoints.MapControllers();  
  64.             });  
  65.         }  
  66.     }  
  67. }  
Run and Test the app
 
Remove the Swagger/index.html and add StaticFiles in the browser URL to load all the static files since we have configured alert inside the javascript file by default the alert is triggered when we navigate to the static file url.
 
 
 
Here is our actual content after loading from the browser.
 
 
 
 Hope this article helps you in a way that how we can use static files inside the Web API.
 
Thanks for your valuable time in reading this. 
 
Keep learning...!


Similar Articles