top of page
Writer's pictureThe Tech Platform

Using Static Files (HTML, CSS,JS) In ASP .NET Core 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.


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 that looks like below.

fig-1


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

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />  
    <title></title>
    <script src="main.js"></script>
    <link href="main.css" rel="stylesheet" />  
</head>
<body>
    <div>
        <h2>Hi, This is Jay<span>👋🏻</span></h2>
        <p>            
            This article is all about how to serve static files using 
            ASP.Net Core 5.0 Web API. Below is the Git hub URL to clone 
            and play around with it.  
            <a target="_blank" 
            href="https://github.com/JayKrishnareddy/StaticFiles"> "Static 
            Files Web API"</a> link.  
        </p>
    </div>
    <img src="AspnetCore.png" />  
</body>
</html>


main.css

h2 {  
    text-align: center;  
    color: blue;  
}  
div {  
    border:1px solid gray;  
    padding:8px;  
}  
p {  
    text-indent:80px;  
    text-align: justify;  
    letter-spacing:3px;  
}  


main.js

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

using Microsoft.AspNetCore.Builder;  
using Microsoft.AspNetCore.Hosting;  
using Microsoft.AspNetCore.HttpsPolicy;  
using Microsoft.AspNetCore.Mvc;  
using Microsoft.Extensions.Configuration;  
using Microsoft.Extensions.DependencyInjection;  
using Microsoft.Extensions.FileProviders;  
using Microsoft.Extensions.Hosting;  
using Microsoft.Extensions.Logging;  
using Microsoft.OpenApi.Models;  
using System;  
using System.Collections.Generic;  
using System.IO;  
using System.Linq;  
using System.Threading.Tasks;  

namespace StaticFiles
{  
    public class Startup    
    {  
        public Startup(IConfiguration configuration)          
        {  
            Configuration=configuration;          
        }  
        
        public IConfiguration Configuration { get; }  
        
        // This method gets called by the runtime. Use this method to add 
        services to the container.  
        public void ConfigureServices(IServiceCollection services)          
        {  
            services.AddControllers();  
            services.AddSwaggerGen(c=>            
            {  
                c.SwaggerDoc("v1", newOpenApiInfo 
                { 
                    Title = "StaticFiles", 
                    Version="v1" 
                });              
            });          
        }  
        
        // This method gets called by the runtime. Use this method to 
        configure the HTTP request pipeline.  
        public void Configure(
                IApplicationBuilder app, 
                IWebHostEnvironment env)          
        {  
            if (env.IsDevelopment())              
            {  
                app.UseDeveloperExceptionPage();  
                app.UseSwagger();  
                app.UseSwaggerUI(c=>c.SwaggerEndpoint 
                        ("/swagger/v1/swagger.json", "StaticFiles v1"));              
            }  
        app.UseFileServer(new FileServerOptions            
        {  
            FileProvider = new PhysicalFileProvider(  
            Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")), 
            RequestPath = "/StaticFiles",  
            EnableDefaultFiles=true            
        }) ;  
        app.UseHttpsRedirection();  
        app.UseRouting();  
        app.UseAuthorization();    
        app.UseEndpoints(endpoints=>            
        {  
            endpoints.MapControllers();              
        });          
    }      
}  


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.

fig-2


Here is our actual content after loading from the browser.




Source: Medium - Nerd For Tech


The Tech Platform

0 comments

Comments


bottom of page