问题
Under ASP.NET and IIS, if I have a virtual path in the form "~/content", I can resolve this to a physical location using the MapPath method:
HttpContext.Server.MapPath("~/content");
How can you resolve a virtual paths to a physical location under an OWIN host?
回答1:
You may use AppDomain.CurrentDomain.SetupInformation.ApplicationBase to get root of your application. With the root path, you can implement "MapPath" for Owin.
I do not know another way yet. (The ApplicationBase
property is also used by Microsoft.Owin.FileSystems.PhysicalFileSystem.)
回答2:
You shouldn't use HttpContext.Server
as it's only available for MVC. HostingEnvironment.MapPath()
is the way to go. However, it's not available for self-hosting owin. So, you should get it directly.
var path = HostingEnvironment.MapPath("~/content");
if (path == null)
{
var uriPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
path = new Uri(uriPath).LocalPath + "/content";
}
回答3:
I'm adding another answer that would work for ASP.NET Core. There is a service IHostingEnvironment, and it's added by the framework.
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();
}
}
回答4:
I have an API running on OWIN self-host (no System.Web) - ran into this issue needing to load a text file where we maintain a list.
This worked for me, found from a co-worker - config.text is right in my root next to web.config:
var path = AppDomain.CurrentDomain.BaseDirectory + "/config.txt";
回答5:
You may have few different implementations of function like
Func<string, string>
provided by different startup code under key like
"Host.Virtualization.MapPath"
and put it into OWIN dictionary. Or you can create basic class like this
public abstract class VirtualPathResolver {
string MapPath(string virtualPath);
}
and pick implementation either by configuration setting, command line parameter or environment variable.
回答6:
The Accepted answer, AppDomain.CurrentDomain.SetupInformation.ApplicationBase, did not work for me under dnx / kestrel - it returned the location of the .dnx runtime and not my webapp route.
This is what worked for me inside OWIN startup:
public void Configure(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
var hostingEnvironment = app.ApplicationServices.GetService<IHostingEnvironment>();
var realPath = hostingEnvironment.WebRootPath + ctx.Request.Path.Value;
// so something with the file here
await next();
});
// more owin setup
}
来源:https://stackoverflow.com/questions/24571258/how-do-you-resolve-a-virtual-path-to-a-file-under-an-owin-host