无法使用IHostingEnvironment获取路径

时间:2018-08-31 13:11:49

标签: startup filepath asp.net-core-webapi environment server.mappath

我要在.Net Core 2.1中创建项目api,在我的startup.cs中,我添加了:

services.AddSingleton<IPathProvider, PathProvider>();  

然后,创建IPathProvider接口和类:

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;
    }
}

然后,在我的api cs文件中,编写代码:

private IHostingEnvironment _hostingEnvironment;

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

现在,在主api中,我将mappath称为:

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

在本地调试时效果很好。但是,当我将其作为新应用程序发布到IIS Web服务器时,它返回的ex.ToString()表示:

  

System.ArgumentNullException:值不能为null。   参数名称:path1      在System.IO.Path.Combine(String path1,String path2)      在E:\ PROJECT EMEC \ LedControlPrj \ LedControlPowerApi \ Controllers \ PowerControlController.cs:line 55中的LedControlPowerApi.Controllers.PowerControlController.GetListPowerSwitch()处

第55行是:var path = MapPath("../DataDen/DataDen.xml");
有人告诉我如何解决此错误吗?谢谢

1 个答案:

答案 0 :(得分:2)

我认为您需要使用ContentRoot而不是WebRoot,因为对于ASP.NET Core 2 API项目,已发布的API项目中没有wwwroot文件夹。

选中此https://github.com/aspnet/Mvc/issues/6688