How do you resolve a virtual path to a file under an OWIN host?

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.)


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

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
        }

Tags:

C#

Owin