[英]ASP .NET 7 run static HTML file with scripts
I am trying to return html
file from my ASP.NET 7 app.我正在尝试从我的 ASP.NET 7 应用程序返回
html
文件。 In that html files i am calling couple of scripts.在那个 html 文件中,我调用了几个脚本。 Html file and scripts exist in same
root
directory: Html 文件和脚本存在于同
root
目录中:
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
:问题是,
scripts
加载了Content-Type: text/html
而不是application/javascript
:
My question is, how to call only .js
file extensions with diffrent content type
using ASP .NET?我的问题是,如何使用 ASP .NET 仅调用具有不同
content type
的.js
文件扩展名?
Your middleware is currently answering every request with the index.html
content.您的中间件当前正在使用
index.html
内容响应每个请求。 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.因此,无论您请求路径
/index.html
还是路径/script.js
都没有关系,服务器将始终响应您的 HTML 文件。
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:如果您只需要提供 static 文件(比如您的 HTML 和 JS 文件),您只需将官方的 static 文件提供程序中间件添加到您的 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.这将返回项目根目录中
/wwwroot
文件夹中包含的每个文件。 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
.所以,如果你想返回
index.html
和所有相关的 JS 文件,只需将它们移动到/wwwroot
目录并向路径/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有关 Microsoft 官方文档的更多信息: https://learn.microsoft.com/en-us/as.net/core/fundamentals/static-files?view=as.netcore-7.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.