How to Map the File Path in Asp.Net Web API

← PrevNext →

Usually, in Asp.Net we would use the Server.MapPath() method for mapping the file path on the server. In this method, you are required to define the virtual path of the file and the method will return the physical path. This is how you get the physical or absolute file path using Server.MapPath() method. var sPath = Server.MapPath("/FilePath/");. Now let me show you how to map file path using Web API.

Map File Path in Web API

To get the physical file path in Web API, you need to use "HostingEnvironment.MapPath()" method.

var sPath = System.Web.Hosting.HostingEnvironment.MapPath("/FilePath/");

You will need to apply this method when your application do not have access to HttpContext.Current properties, under the "System.Web" namespace. By default, an Asp.Net page refers to the System.Web to get access to various methods in the HttpContext class.

For example, "Server.CreateObject" or "Server.MapPath()" etc.

However, if you are "Self Hosting" a Web API application, then you will not have access to the HttpContext class. Typically, a Self Hosting application runs on its own process, that is, you are not hosting the application on the IIS. Therefore, the preferred method for getting the physical file path in a Web API application would be HostingEnvironment.MapPath().

Ref.: HostingEnvironment.MapPath Method

← PreviousNext →