问题描述
我在 .NET Core 中有一个 Web 应用程序,它为某个文件夹中的所有文件提供服务。现在在提供文件之前,需要一个密码。 这段代码够不够用还是有漏洞?
using DownloadFiles.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace DownloadFiles.Controllers
{
public class HomeController : Controller
{
private readonly Pass _pass;
private readonly IHostingEnvironment _webHostEnvironment;
public HomeController(IHostingEnvironment webHostEnvironment,IOptions<Pass> pass)
{
_webHostEnvironment = webHostEnvironment;
_pass = pass.Value;
}
[HttpGet]
public IActionResult Index()
{
string Path1 = _webHostEnvironment.WebrootPath + "\\..\\Files\\";
string[] Files = Directory.GetFiles(Path1);
List<FilesModel> FilesList = new List<FilesModel>();
foreach (string item in Files)
{
FilesModel file = new FilesModel
{
FileName = Path.GetFileName(item),FilePath = "Home/DownloadFile/"
};
file.FilePath += file.FileName;
FilesList.Add(file);
}
return View(FilesList.OrderBy(x => x.FileName));
}
[HttpGet]
public IActionResult DownloadFile(string id)
{
string FileName = id;
if (string.IsNullOrEmpty(FileName))
{
return RedirectToAction("Index");
}
PwModel PW = new PwModel
{
FileName = FileName
};
return View(PW);
}
[HttpPost]
public IActionResult DownloadFile(PwModel PassModel)
{
string Pass = PassModel.Password;
if (string.IsNullOrEmpty(PassModel.FileName))
{
return RedirectToAction("Index");
}
if (!string.Equals(Pass,_pass.Password))
{
ModelState.AddModelError("","Incorrect password!");
return View();
}
string FilePath = _webHostEnvironment.WebrootPath + "\\..\\Files\\" + PassModel.FileName;
byte[] fileBytes = System.IO.File.ReadAllBytes(FilePath);
return File(fileBytes,"application/x-msdownload",PassModel.FileName);
}
[responsecache(Duration = 0,Location = responsecacheLocation.None,NoStore = true)]
public IActionResult Error()
{
return View(new Errorviewmodel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
上面是控制器。以下是索引视图:
@model IEnumerable<DownloadFiles.Models.FilesModel>
@{
ViewData["Title"] = "Home";
}
<style>
a:hover {
text-decoration: none;
}
</style>
@{
int count1 = 0;
<table class="table table-responsive table-condensed table-hover table-bordered">
<thead>
<tr>
<th>No.</th>
<th>File Name</th>
<th>Download</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
count1++;
string SerialNum = count1.ToString() + ".";
string Title1 = "Download " + item.FileName;
<tr>
<td>@SerialNum</td>
<td><a href="@item.FilePath" style="color: black">@item.FileName</a></td>
<td><a title="@Title1" class="btn btn-success" href="@item.FilePath"><span class="glyphicon glyphicon-download-alt"></span></a></td>
</tr>
}
</tbody>
</table>
}
我只是想确保用户不能只在地址栏中写一个 url 并获取绕过密码的文件。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)