Using ASP.NET Core 2.1
, I'm trying to load the same static file locally on my dev machine (through Visual Studio 2017) and after the website has been published to the hosting environment (Azure Web Apps).
Consider the directory hierarchy in which the static file (file.xml
) to be served resides inside the web root:
wwwroot
css
images
js
xml
file.xml
Here's my controller to load the file:
public class DevelopmentController : Controller
{
private readonly IHostingEnvironment _env;
public DevelopmentController(IHostingEnvironment env)
{
_env = env;
}
public async Task<string> Test()
{
string result = "";
// Test Code Here
XmlDocument doc = new XmlDocument();
doc.Load(Path.Combine(_env.WebRootPath, "xml", "file.xml"));
return result;
}
}
This loads the file locally on my dev machine, however, once the web app is published to Azure, I get the following error:
DirectoryNotFoundException: Could not find a part of the path 'D:\home\site\wwwroot\wwwroot\xml\file.xml'
No matter what I try, I cannot seem to load the file after it has been published to Azure.
NOTE: In ASP.NET MVC 5
, I used to be able to use the Server.MapPath()
function to load a static file, which worked both locally and in Azure. For example:
doc.Load(System.Web.HttpContext.Current.Server.MapPath("~/xml/file.xml"));
But since upgrading to ASP.NET Core 2.1
, I can't figure out the proper way to do this, that will also work when hosted on Azure.
These are the Microsoft Docs, I've used as reference: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-2.1&tabs=aspnetcore2x
UPDATE
In case anyone else experiences the same issue, this is what the problem was:
If you drag and drop a folder into Solution Explorer
, the reference does not get automatically added to the .csproj
file.
You can check your .csproj
file by right clicking on the project and selecting Edit {Project Name}.csproj
. For any extra folders you've added to the wwwroot
directory, you should see something like:
<ItemGroup>
<Folder Include="wwwroot\myfolder\" />
</ItemGroup>
If you don't see that, then it won't be published to Azure.
NOTE: If you see <None ...
, then that means that the folder has been set to be excluded from publishing.
<ItemGroup>
<None Include="wwwroot\myexcludedfolder\"
</ItemGroup>
SOLUTION
I just deleted the folder that I had drag and dropped into Solution Explorer, and instead right clicked wwwroot
to create the folder that way.