Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve static files from .NET Core API?

The API is using .NET Core 3.1 and the folder structure is as follows:

Solution

--Project1

--Project2

Where Project 2 depends on Project 1 and is the entry point.

The API is hosted on kubernetes and a NFS share is mounted at /storage. The API will need to retrieve and serve files in this file share. So what I did was using the following in my startup.cs in Project2:

app.UseFileServer(new FileServerOptions()
{
    FileProvider = new PhysicalFileProvider(
    Path.Combine(Directory.GetCurrentDirectory(), @"storage")),//this will return /app/storage 
    RequestPath = new PathString("/resources")
});

I know one of the file is there by checking:

  System.IO.File.Exists(@"/app/storage/test.JPG");

However, when I tried to access the file by going to http://myapiurl/resources/test.JPG, I always got a 404 not found.

I was wondering what I was missing?

like image 894
SamulP Avatar asked Nov 01 '25 10:11

SamulP


2 Answers

You're using UseFileServer, but you're not enabling directory browsing nor serving default files, so I'd recommend narrowing instead to using UseStaticFiles.

The easiest way to enable this is to just place the following in your Startup.cs file in your Configure() method.

app.UseStaticFiles(new StaticFileOptions 
{
  FileProvider = new PhysicalFileProvider(
    Path.Combine(env.ContentRootPath, "storage")),
    RequestPath = "/resources"
});

My guess for why this isn't working for you is that Directory.GetCurrentDirectory, when running in K8 isn't yielding the same path you see when running locally, so it's not ultimately pointing at /app/storage (which is why your File.Exists check works fine because you're not building the path out dynamically).

Use some logging to verify that it's pulling from the right path in your configuration at runtime.

like image 149
Whit Waldo Avatar answered Nov 03 '25 01:11

Whit Waldo


I had a similar problem with static files after switching from AppService to k8s with ingress. It turned out to be problem with case-sensitivity in the URL. Some directories were uppercase, but in paths I had all lowercase letters. It was working locally on Windows and on AppService but not on k8s.

like image 43
rfff Avatar answered Nov 03 '25 00:11

rfff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!