0

I'm creating project api in .Net Core 2.1, in my startup.cs, I added:

services.AddSingleton<IPathProvider, PathProvider>();  

After that, reate IPathProvider interface and class:

public interface IPathProvider
{
    string MapPath(string path);
}

public class PathProvider : IPathProvider
{
    private IHostingEnvironment _hostingEnvironment;

    public PathProvider(IHostingEnvironment environment)
    {
        _hostingEnvironment = environment;
    }

    public string MapPath(string path)
    {
        var filePath = Path.Combine(_hostingEnvironment.WebRootPath, path);
        return filePath;
    }
}

And then, in my api cs file, I write code:

private IHostingEnvironment _hostingEnvironment;

    public PowerControlController(IHostingEnvironment environment)
    {
        _hostingEnvironment = environment;
    }
public string MapPath(string path)
    {
        var filePath = Path.Combine(_hostingEnvironment.WebRootPath, path);
        return filePath;
    }

Now, in main api, I call mappath:

public ActionResult<string> GetListPowerSwitch()
    {
        try
        {
            var path = MapPath("../DataDen/DataDen.xml");
            return path;
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }

It's work well when debug in local. But, when I publish it to IIS Web Server as new application, it's return ex.ToString() that:

System.ArgumentNullException: Value cannot be null. Parameter name: path1 at System.IO.Path.Combine(String path1, String path2) at LedControlPowerApi.Controllers.PowerControlController.GetListPowerSwitch() in E:\PROJECT EMEC\LedControlPrj\LedControlPowerApi\Controllers\PowerControlController.cs:line 55

Line 55 is: var path = MapPath("../DataDen/DataDen.xml");
Anyone tell me how to fix this bug ? Thanks

Đồng Vọng
  • 159
  • 3
  • 11

1 Answers1

2

I think you need to use ContentRoot instead of WebRoot because for ASP.NET Core 2 API project there is no wwwroot folder in published API project.

Check this https://github.com/aspnet/Mvc/issues/6688

Mohsin Mehmood
  • 4,156
  • 2
  • 12
  • 18
  • Thanks, but it's still fail. But have a solution from your link, I added this code `if (string.IsNullOrWhiteSpace(env.WebRootPath)) env.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");` to startup Configure and api is work well. – Đồng Vọng Sep 01 '18 at 07:49
  • 1
    Yep. Using `ContentRootPath` instead of `WebRootPath` worked. – m_kramar Mar 28 '19 at 22:29