简体   繁体   中英

ASP .NET 7 run static HTML file with scripts

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 :

在此处输入图像描述

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

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/as.net/core/fundamentals/static-files?view=as.netcore-7.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM