禁止访问非授权目录,解析并处理用户输入的文件路径参数,使用虚拟路径来代替物理路径等。
示例代码:
- 禁止访问非授权目录:
在asp.net core中,可以通过在Web.config文件中加入如下语句来防止访问非授权目录:
- 解析并处理用户输入的文件路径参数:
在asp.net core中,可以通过使用相关函数来正确处理用户输入的文件路径参数,例如:
public async Task Download(string fileName)
{
var path = Path.Combine(_rootPath, fileName);
if (!Path.GetFullPath(path).StartsWith(_rootPath))
{
return NotFound();
}
var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
return File(fileStream, MimeTypes.GetMimeType(path), fileName);
}
- 使用虚拟路径来代替物理路径:
在asp.net core中,可以使用虚拟路径来代替物理路径,例如:
services.Configure(options =>
{
options.AllowAccessOutsideOfRoot = false;
});
app.UseStaticFiles(new StaticFileOptions
{
ServeUnknownFileTypes = true,
DefaultContentType = "application/octet-stream",
FileProvider = new PhysicalFileProvider(_rootPath),
RequestPath = new PathString("/files")
});