【问题标题】:How do I access a directory path in asp.net core from server side code?如何从服务器端代码访问 asp.net 核心中的目录路径?
【发布时间】:2019-12-19 14:36:01
【问题描述】:

我正在尝试从服务器端代码获取当前目录路径。在 asp.net 中,我们使用HttpContext.Current.Server.MapPath 来获取路径。但它与 asp.net 核心不同,我们应该使用IHostingEnvironment 来获取路径。据我所知,它仅在 StartUp 类和 Controllers 中使用,但我想做的是在服务器端类中使用它。我该怎么做?

我尝试将IHostingEnvironment 值传递给服务器端类的构造函数,但它设置为null。 StartUp 类中没有添加任何其他内容。

我还尝试在 Internet 上寻求任何帮助,但无法相信没有任何东西可以帮助我在服务器端类中设置值。

这是我的代码示例:

public class PathHelper
    {
        private static IHostingEnvironment _hostingEnvironment;


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

        public static string RootPath
        {
            get
            {
                return _hostingEnvironment.ContentRootPath;
            }
        }

我得到的错误是

构造函数级别的空引用。

【问题讨论】:

    标签: c# asp.net-core hosting environment


    【解决方案1】:

    这不是最好的选择,但这是我目前正在做的事情。

    我将IHostingEnvironment 传递给静态类以供全局使用,并在Startup.cs 中的Configure 方法上初始化。

    public static class Context
    {
        public static IHostingEnvironment HostingEnvironment;
    }
    

    Startup.cs 中的Configure 方法上赋值

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
        {
            //.....
            namespace.Context.HostingEnvironment = env;
        }
    

    【讨论】:

      猜你喜欢
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 2013-10-10
      • 2021-04-14
      • 2018-11-21
      • 1970-01-01
      相关资源
      最近更新 更多