1

I have the following folder structure on my ASP.NET Core server (.NET5.0):

  • wwwroot\MyXmlFiles\foo.xml

The files can be accessed as static files as https://myserver.com/MyXmlFiles/foo.xml. However, I would like to make the file available via WebApi controller action:

[HttpGet("{uri}")]
public string Get(string uri)
{
     // How do I return the foo.xml file content here 
     // without redirection or loading it to memory?
}
user256890
  • 3,396
  • 5
  • 28
  • 45
  • If you do not configure the path through the startup.cs file, can you directly return a path view you need in the controller layer? – Tupac Oct 18 '21 at 08:06

1 Answers1

0

You can read a content of file from the disk and return from the controller:

[HttpGet("{uri}")]
public IActionResult Get(string uri)
{
    var path = GetPathFromUri(uri);
    using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
    {
        return new FileStreamResult(stream, "text/xml")
    }
}

You have to write GetPathFromUri method that transforms uri to the physical path (e.g “MyXmlFiles/foo.xml” -> “wwwroot\MyXmlFiles\foo.xml”)

instanceMaster
  • 456
  • 3
  • 12
  • 1
    Generally a very bad idea to forward user crafted parameters directly into filesystem. File.ReadAllText is not limited to web server root. At very least sanitize filename to only contain whitelisted chars (that do not include / \). File.ReadAllText() reads file into memory. OP wanted to avoid that. – Tedd Hansen Oct 20 '21 at 20:44
  • @yfranz, thank you for your contribution. Your proposal assumes that the xml file is small enough to fit into the memory of the server, which is not always the case. I was looking for a solution that bypasses the memory. – user256890 Oct 21 '21 at 07:40
  • In this case you need to stream it. Check this question: https://stackoverflow.com/questions/13983190/actionresult-returning-a-stream/13984181 – instanceMaster Oct 21 '21 at 21:50
  • @tedd-hansen Totally agree. This is why GetPathFromUri was introduced. – instanceMaster Oct 21 '21 at 21:54
  • I've changed my solution to use stream. – instanceMaster Oct 21 '21 at 21:59