Mister Epic
Mister Epic

Reputation: 16743

Finding the request's physical path

In ASP.Net 5, how do I retrieve the physical path of a request if I'm creating ASP.Net middleware?

public async Task Invoke(HttpContext context)
{
    var request = context.Request

Previously I would have either leveraged:

HttpServerUtility.MapPath()

or

System.Web.Request.PhysicalPath()

The new Microsoft.AspNet.Http.Request object only has a Path property, and I'm unclear how to convert the request path to the filesystem path.

Upvotes: 4

Views: 1161

Answers (1)

Sherif Elmetainy
Sherif Elmetainy

Reputation: 4502

EDIT April 2021

My original answer used IHostingEnvironment which became obsolete from version 3.0. If you are using version 3.0 or later use IWebHostEnvironment interface instead. Otherwise see the original answer below if you are using an older version.

Thanks @dan-jagnow for bringing this to my attention.

public class PhysicalPathMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IWebHostEnvironment _hostingEnvironment;
    public PhysicalPathMiddleware(RequestDelegate next, IWebHostEnvironment hostingEnvironment)
    {
        _next = next;
        _hostingEnvironment = hostingEnvironment;
    }
    public async Task Invoke(HttpContext context)
    {
        var physicalFileInfo = _hostingEnvironment.WebRootFileProvider.GetFileInfo(context.Request.Path);
        var physicalFilePath = physicalFileInfo.PhysicalPath;
    }
}

Original Answer From 2015

You can use IHostingEnvironment service as follows:

public class PhysicalPathMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IHostingEnvironment _hostingEnvironment;
    public PhysicalPathMiddleware(RequestDelegate next, IHostingEnvironment hostingEnvironment)
    {
        _next = next;
        _hostingEnvironment = hostingEnvironment;
    }
    public async Task Invoke(HttpContext context)
    {
        var physicalFileInfo = _hostingEnvironment.WebRootFileProvider.GetFileInfo(context.Request.Path);
        var physicalFilePath = physicalFileInfo.PhysicalPath;
    }
}

Upvotes: 4

Related Questions