HttpContext.Current is null in the WebAPI project



  • VS2013
  • .NET 4.5
  • WebAPI project

I try to get a "MapPath" path for some dir, but in the WebAPI project "HttpContext.Current" is NULL

How example:

string path = HttpContext.Current.Server.MapPath("~/Some/Path");

Please. Help me!

2 answers

I am currently using this solution in MVC4 and it's working well:


public static class WebApiConfig { public static string UrlPrefix { get { return "api"; } } public static string UrlPrefixRelative { get { return "~/api"; } }

public static void Register(HttpConfiguration config)
        name: "DefaultApi",
        routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }



public class MvcApplication : System.Web.HttpApplication { ...

protected void Application_PostAuthorizeRequest()
    if (IsWebApiRequest())

private bool IsWebApiRequest()
    return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative);


This solution has the added bonus that we can fetch the base URL in javascript for making the AJAX calls:


<body> @RenderBody()

<script type="text/javascript">
    var apiBaseUrl = '@Url.Content(ProjectNameSpace.WebApiConfig.UrlPrefixRelative)';

@RenderSection("scripts", required: false) 

and then within our Javascript files/code we can make our webapi calls that can access the session:

$.getJSON(apiBaseUrl + '/MyApi') .done(function (data) { alert('session data received: ' + data.whatever); }) );


I realize session and REST don't exactly go hand in hand but is it not possible to access session state using the new Web API? HttpContext.Current.Session is always null.


Too many commands? Learning new language? is a free tool that allows you to save your favorite scripts and commands, then quickly find and copy-paste your commands with just few clicks.

Boost your daily productivity with!

Post Answer