Microsoft Web API: How to do a Server.MapPath

asp.net-web-api

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"

Best Answer

You can use HostingEnvironment.MapPath in any context where System.Web objects like HttpContext.Current are not available (e.g also from a static method).

var mappedPath = System.Web.Hosting.HostingEnvironment.MapPath("~/SomePath");

See also What is the difference between Server.MapPath and HostingEnvironment.MapPath?