如何在OWIN主机下解析文件的虚拟路径?

在ASP.NET和IIS下,如果我有“〜/ content”forms的虚拟路径,我可以使用MapPath方法将其解析为物理位置:

HttpContext.Server.MapPath("~/content"); 

如何在OWIN主机下解析到物理位置的虚拟路径?

您可以使用AppDomain.CurrentDomain.SetupInformation.ApplicationBase来获取应用程序的根目录。 使用根路径,您可以为Owin实现“MapPath”。

我还不知道另一种方式。 ( Microsoft.Owin.FileSystems.PhysicalFileSystem也使用ApplicationBase属性。)

您不应该使用HttpContext.Server因为它仅适用于MVC。 HostingEnvironment.MapPath()是要走的路。 但是,它不适用于自托管owin。 所以,你应该直接得到它。

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

我正在添加另一个适用于ASP.NET Core的答案。 有一个服务IHostingEnvironment,它由框架添加。

 public class ValuesController : Controller { private IHostingEnvironment _env; public ValuesController(IHostingEnvironment env) { _env = env; } public IActionResult Get() { var webRoot = _env.WebRootPath; var file = Path.Combine(webRoot, "test.txt"); File.WriteAllText(file, "Hello World!"); return OK(); } } 

您可能没有几个不同的function实现

 Func 

由密钥之类的不同启动代码提供

 "Host.Virtualization.MapPath" 

并把它放入OWIN词典。 或者你可以像这样创建基本类

 public abstract class VirtualPathResolver { string MapPath(string virtualPath); } 

并通过配置设置,命令行参数或环境变量选择实现。

接受的答案AppDomain.CurrentDomain.SetupInformation.ApplicationBase在dnx / kestrel下对我没有用 – 它返回了.dnx运行时的位置,而不是我的webapp路由。

这对我在OWIN创业中的作用是:

 public void Configure(IApplicationBuilder app) { app.Use(async (ctx, next) => { var hostingEnvironment = app.ApplicationServices.GetService(); var realPath = hostingEnvironment.WebRootPath + ctx.Request.Path.Value; // so something with the file here await next(); }); // more owin setup }