HostingEnvironment.MapPath不适用于Owin自托管选项

时间:2014-07-14 02:52:34

标签: asp.net owin asp.net-web-api2

我正在尝试在基于Owin的自托管服务器上加载文件。

WebApp.Start<Startup>("http://localhost:3001/");

以下是我如何映射路径:

var path = HostingEnvironment.MapPath("~");

它总是返回null!

另一方面,如果网站托管在IIS(或快递)中,则路径的值是正确的。 如何为自托管的owin填充此值?

2 个答案:

答案 0 :(得分:1)

由于owin自托管不使用iis而不是虚拟路径,因此应使用绝对路径。

var path = HostingEnvironment.MapPath("~");
if (path == null)
{
    var uriPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
    path = new Uri(uriPath).LocalPath;
}

答案 1 :(得分:0)

在dnx下在OWIN下运行时,我发现许多建议的解决方法围绕读取当前应用程序域将返回.dnx runttime文件夹 - 而不是Web应用程序位置。

这是在OWIN创业公司内部对我有用的东西:

public void Configure(IApplicationBuilder app)
        {

            app.Use(async (ctx, next) =>
            {
                var hostingEnvironment = app.ApplicationServices.GetService<IHostingEnvironment>();
                var realPath = hostingEnvironment.WebRootPath + ctx.Request.Path.Value;

                // do something with the real file -path

                await next();
            });
相关问题