gpt4 book ai didi

c# - 为什么我无法访问通过 POST 请求以编程方式添加的静态文件?

转载 作者:行者123 更新时间:2023-12-04 01:06:33 25 4
gpt4 key购买 nike

我正在尝试制作一个基本的 .NET API 来管理媒体集合(图像和视频)。

我已经将 webroot 配置为一个名为“site”的文件夹,在该文件夹中有一个名为“media”的文件夹,其中存储了这些文件。我可以通过加载 https://localhost:5001/site/media/smush.jpg 来访问保存在/site/media/Smush.jpg 中的测试媒体文件 - 这会按预期提供图像。

我创建了一个方法,它从我的前端接收包含表单数据的 POST 请求,该方法使用文件流将文件保存到 webroot,代码如下:

[HttpPost]
[Route("/media/add")]
public async Task<HttpResponseMessage> MediaAdd()
{
try
{
//get the form
var form = HttpContext.Request.Form;

//if there's a route, add it into the filepath, otherwise leave it out and have the filepath go straight to media (this prevents an exception if route is blank)
string filePath = form["route"] == "" ? Path.Combine(_hostingEnvironment.WebRootPath, "media") : Path.Combine(_hostingEnvironment.WebRootPath, "media", form["route"]);

//get the first (should be only) image - DO WE WANT TO BE ABLE TO ADD MULTIPLE IMAGES? PROBABLY TBH
IFormFile image = form.Files.First();

if (image.Length > 0)
{
//check the directory exists - create it if not
if (!Directory.Exists(filePath)) {
Directory.CreateDirectory(filePath);
}

using (Stream fileStream = new FileStream(Path.Combine(filePath, form["filename"]), FileMode.Create))
{
await image.CopyToAsync(fileStream);
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
else {
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
catch (Exception e)
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}

我的前端提交了一个路由、文件名和媒体文件,这是用来保存图像的。这一切都很好;我可以提交一张路径为“test”、名称为“test.jpg”的图像,API 将文件正确存储在/site/media/test/test.jpg。我可以在解决方案中查看文件并查看图像的预览,就像 Smush.jpg 一样。

Demonstration that the test file is added to the APIs local files correctly

但是,尝试加载 https://localhost:5001/site/media/test/test.jpg 会导致 404。为什么会这样?我可以不通过代码将文件添加到 webroot 中,并让它们作为静态文件访问,就像我将它们添加到我的 IDE 中的解决方案一样吗?有没有其他方法可以处理这个问题?

我正在使用 .NET 5.0,并且有app.UseStaticFiles(); 在 Startup.cs 的 Configure() 中。

抱歉,如果这是重复的,但我找不到其他类似的东西。

编辑:再次检查时,似乎我的文件不是在 https://localhost:5001/site/media,而是在 https://localhost:5001/media。我不确定我之前是如何通过 https://localhost:5001/site/media/Smush.jpg 访问 Smush.jpg 的。

似乎 webroot 没有作为访问其中文件的 URL 的一部分包含在内。

就像现在一样,我已经得到了我想要它做的事情。

最佳答案

首先是@Heinzi 指出的安全问题......

string filePath = form["route"] == "" ? Path.Combine(_hostingEnvironment.WebRootPath, "media") : Path.Combine(_hostingEnvironment.WebRootPath, "media", form["route"]);

如果用户发送 form.route == "../../"而不是更新 appsettings.json 文件而不是图像怎么办?

检查 this如果您打算将此代码发布到生产环境并确保您只接受图像文件,请记住这一点。

另一方面,如果您从不同于 wwwroot 的文件夹中提供静态文件,请使用 this configuration

关于c# - 为什么我无法访问通过 POST 请求以编程方式添加的静态文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66279493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com