Access static files on server from RCL

738 views Asked by At

I've read dozens of questions but none seem to work for me. I'm not using IIS. I'm using ASP.Net Core 3.1 with Kestrel.

I have a Razor Class Library with a resources folder, in that I have folders like css, js, content, etc. I use this library so all of my common Web Api projects can share common files instead of duplicating them everywhere. To do this, I followed the guide from here. Please see there for how Startup is configured.

That works great, I can access those files by going to e.g. localhost/css/site.css. In my cshtml files, I can include that file by doing <link rel="stylesheet" href="~/css/site.css"/>

The problem arises when I try to access those files from a controller. I have a sister folder to css called content which contains json files. I can view that file by going to localhost/content/test.json, but I can't figure out how to access it from a controller.

What I'd like to do is make an HTTP request to ~/content/test.json and download its contents, but the path is not found.

I've tried using Url.Content to map a relative path to the absolute path, but it doesn't work.

var url = Url.Content("~/content/test.json"); // spits out "/content/test.json"

I've DI'd IWebHostEnvironment into the controller and tried to access the ContentRootFileProvider and the ContentRootPath and WebRootPath, but those paths aren't right either. They are pointing to my currently running service's wwwroot's parent and wwwroot, respectively.

I've tried creating my own file provider:

var filesProvider = new ManifestEmbeddedFileProvider(GetType().Assembly, "resources");
var content = filesProvider.GetDirectoryContents("content");
var fileInfo = filesProvider.GetFileInfo(Path.Combine("content", "test.json"));

This successfully finds the file and claims it exists, but the fileInfo's PhysicalPath is always null.

I just want to do something like this:

string SomeMagicMapFunction(string s) => ????

var webClient = new WebClient();
var json = webClient.DownloadString(SomeMagicMapFunction("~/content/test.json"));

Where am I going wrong? Any pointers are appreciated.

0

There are 0 answers