Home > Back-end >  ASP .NET 7 run static HTML file with scripts
ASP .NET 7 run static HTML file with scripts

Time:01-29

I am trying to return html file from my ASP NET 7 app. In that html files i am calling couple of scripts. Html file and scripts exist in same root directory:

using Microsoft.Net.Http.Headers;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// middleware
app.Use(async (context, next) =>
{
    var html = await File.ReadAllTextAsync("index.html");

    context.Response.ContentType = "text/html";

    await context.Response.WriteAsync(html);

    await next();
});

app.Run();

The problem is, that scripts are loaded with Content-Type: text/html instead of application/javascript:

enter image description here

My question is, how to call only .js file extensions with diffrent content type using ASP .NET?

CodePudding user response:

Your middleware is currently answering every request with the index.html content. So, it doesn't matter if you are requesting the path /index.html or the path /script.js, the server will always respond with your HTML file.

If you only need to provide static files (like your HTML and JS files), you can do it by just adding the official static file provider middleware to your Startup:

using Microsoft.Net.Http.Headers;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseStaticFiles()  // Static file provider

app.Run();

This will return every file included in the /wwwroot folder in the root of the project. So, if you want to return the index.html and all the related JS files, just move them to the /wwwroot directory and make a request to the path /index.html.

More information on the official Microsoft documentation: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-7.0

  • Related