1.新建空的net core项目
2.如果需要提供目录浏览功能,需要注册目录浏览服务,静态文件服务默认已经加入
public void ConfigureServices(IServiceCollection services)
{
services.AddDirectoryBrowser();
}
3 配置应用程序
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseDirectoryBrowser();
}
3.在wwwroot下面随意增加index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title> Asp.net core</title>
</head>
<body>
<h1>File Server Demo</h1>
</body>
</html>
4.运行应用程序,可以看到该文件,并可以访问
5.也可以允许用户访问web目录下的个别目录
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseDirectoryBrowser(new DirectoryBrowserOptions()
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "pics"))
});
}
6.也可以启动多个web根目录,需要设定RequestPath
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Assets")),
RequestPath = new PathString("/Public/Assets")
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions()
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "pics"))
});
}
7.修改web根目录下的index.html,添加引用非默认目录下的img
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title> Asp.net core</title>
</head>
<body>
<h1>File Server Demo</h1>
<hr />
<img alt="test" src="/Public/assets/test.jpg"
</body>
</html>
8.运行程序,访问index.html可以看到该图片
9.添加默认文件
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDefaultFiles();
app.UseStaticFiles();
}
10.在webroot下面添加default.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Default</title>
</head>
<body>
<h1>Default</h1>
</body>
</html>
11.运行,则会直接显示default.html
12.也可以更改默认文件
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("home.html");
options.DefaultFileNames.Add("home.htm");
app.UseDefaultFiles(options);
app.UseStaticFiles();
}
13.在webroot下面增加home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>home</title>
</head>
<body>
<h1>home</h1>
</body>
</html>
14.运行,则可以直接显示home.html