I'm using static files middleware to access customer specific resources located outside wwwroot. These resources include CSS and image files, and are accessible at ~/resources. For example, customer-specific css is located here :
<link rel="stylesheet" href="~/resources/css/customer.css" />
Now I would like to serve a static html file located in ~/resources/html/static.html. I created a model which contains only a HtmlString property, and I wish to inject the content of static.html inside a standard cshtml using this model. Here is my controller action :
public IActionResult MentionsLegales()
{
var filePath = IO.Path.Combine(
_env.ContentRootPath, "PersonnalisationClient", _config["PersonnalisationClient:NomClient"], "html", "mentionslegales.html");
var mentionsLegalesModel = new MentionsLegalesModel();
if (IO.File.Exists(filePath))
mentionsLegalesModel.Content = new Microsoft.AspNetCore.Html.HtmlString(IO.File.ReadAllText(filePath));
else
{
_logger.LogWarning($"Le fichier {filePath} est introuvable");
mentionsLegalesModel.Content = new Microsoft.AspNetCore.Html.HtmlString(string.Empty);
}
return View(mentionsLegalesModel);
}
As you can see, here I access the file through its physical path. It's working but I'm not satisfied with this solution. I wanted to read the file through its server path, which is ~/resources/html/mentionslegales.html, but I don't know how to do that. Apparently in non-Core MVC one could use Server.MapPath for such purpose, but I couldn't find an equivalent in MVC core. Do you have any ideas ?
Path.Combine(_env.ContentRootPath, "resources/html/mentionslegales.html")allows you to use the server path (as a relative path though)IO.Path.Combine( _env.ContentRootPath, "PersonnalisationClient", _config["PersonnalisationClient:NomClient"], "html", "mentionslegales.html");looks to me like you're building the path manually, rather that lettingPath.Combinecombine it for you. There is no equivalent ofServer.MapPathin ASP net core, so usingIHostingEnvironmentis your only option.