C
C#7mo ago
Lionel Bovy

Serving static files via a Web API (REST)

Hello, I'd like to set up an image upload system via a REST API in ASP.NET Core 6. I tried to configure my Program.cs, but when I try to get the path via the environment in my service, it's set to Microsoft.Extensions.FileProviders.NullFileProvider and I get a null path. Here's my Program.cs: https://pastebin.com/9hJmEKJn Here is the code where I encounter the problem:
public class LocalFileUploadService : IFileUploadService
{
private readonly IWebHostEnvironment _environment;

public LocalFileUploadService(IWebHostEnvironment environment)
{
_environment = environment;
}

public async Task<string> UploadFileAsync(IFormFile file, string fileName)
{
var fileExtension = Path.GetExtension(file.FileName);
var filePath = Path.Combine(_environment.WebRootPath, "uploads", fileName + fileExtension);

using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}

return fileName;
}

// ...
}
public class LocalFileUploadService : IFileUploadService
{
private readonly IWebHostEnvironment _environment;

public LocalFileUploadService(IWebHostEnvironment environment)
{
_environment = environment;
}

public async Task<string> UploadFileAsync(IFormFile file, string fileName)
{
var fileExtension = Path.GetExtension(file.FileName);
var filePath = Path.Combine(_environment.WebRootPath, "uploads", fileName + fileExtension);

using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}

return fileName;
}

// ...
}
Pastebin
Program.cs - Pastebin.com
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
2 Replies
Kiel
Kiel7mo ago
https://stackoverflow.com/questions/59304961/how-can-i-get-access-to-the-iwebhostenvironment-from-within-an-asp-net-core-3-co#comment104851604_59305508
OK I finally reproduced the issue. The API template you use doesn't create a wwwroot folder, which is why you get a NullFileProvider. If you add a wwwroot folder (it can be empty), you'll have a PhysicalFileProvider.
I'm unsure why asp.net works in this way...maybe there's a more robust solution for what you're trying to do - what's your end goal - determining the physical file location to save files in? Is Directory.GetCurrentDirectory() sufficient for your needs?
Lionel Bovy
Lionel Bovy7mo ago
Thank you very much for the message, I was not aware of this behavior. I also tried it and it works as expected. To answer the second part, I just wanted to make a folder where we could put user avatars and access them directly without having to create an additional endpoint.