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?
}
1
  • 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? Commented Oct 18, 2021 at 8:06

1 Answer 1

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”)

Sign up to request clarification or add additional context in comments.

5 Comments

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.
@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.
In this case you need to stream it. Check this question: stackoverflow.com/questions/13983190/…
@tedd-hansen Totally agree. This is why GetPathFromUri was introduced.
I've changed my solution to use stream.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.