[asp.net-web-api] Microsoft Web API: How do you do a Server.MapPath?

Since Microsoft Web API isn't MVC, you cannot do something like this:

var a = Request.MapPath("~");

nor this

var b = Server.MapPath("~");

because these are under the System.Web namespace, not the System.Web.Http namespace.

So how do you figure out the relative server path in Web API ?
I used to do something like this in MVC:

var myFile = Request.MapPath("~/Content/pics/" + filename);

Which would give me the absolute path on disk:

"C:\inetpub\wwwroot\myWebFolder\Content\pics\mypic.jpg"

This question is related to asp.net-web-api

The answer is


Little bit late answering that but there we go.

I could solve this using Environment.CurrentDirectory


The selected answer did not work in my Web API application. I had to use

System.Web.HttpRuntime.AppDomainAppPath

You can try like:

var path="~/Image/test.png"; System.Web.Hosting.HostingEnvironment.MapPath( @ + path)


As an aside to those that stumble along across this, one nice way to run test level on using the HostingEnvironment call, is if accessing say a UNC share: \example\ that is mapped to ~/example/ you could execute this to get around IIS-Express issues:

#if DEBUG
    var fs = new FileStream(@"\\example\file",FileMode.Open, FileAccess.Read);
#else
    var fs = new FileStream(HostingEnvironment.MapPath("~/example/file"), FileMode.Open, FileAccess.Read);
#endif

I find that helpful in case you have rights to locally test on a file, but need the env mapping once in production.


I can't tell from the context you supply, but if it's something you just need to do at app startup, you can still use Server.MapPath in WebApiHttpApplication; e.g. in Application_Start().

I'm just answering your direct question; the already-mentioned HostingEnvironment.MapPath() is probably the preferred solution.


string root = HttpContext.Current.Server.MapPath("~/App_Data");

Since Server.MapPath() does not exist within a Web Api (Soap or REST), you'll need to denote the local- relative to the web server's context- home directory. The easiest way to do so is with:

string AppContext.BaseDirectory { get;}

You can then use this to concatenate a path string to map the relative path to any file.
NOTE: string paths are \ and not / like they are in mvc.

Ex:

System.IO.File.Exists($"{**AppContext.BaseDirectory**}\\\\Content\\\\pics\\\\{filename}");

returns true- positing that this is a sound path in your example