0

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?

3
  • 2
    Right now you are always returning your index.html for every request, even for the scripts. You should look into using the StaticFileMiddleware instead which will handle this for you. Commented Jan 27, 2023 at 12:08
  • Thanks, i will take a look! In a meantime can you produce an answer ? Commented Jan 27, 2023 at 12:09
  • 1
    Try to call "app.UseStaticFiles();" just before you code learn.microsoft.com/en-us/aspnet/core/fundamentals/… Commented Jan 27, 2023 at 13:46

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

yup, i did that and it worked. The only thing you need to do to put your script.js files into wwwroot folder, use UseStaticFiles extension and then everything works fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.