HttpContext.Current is null in the WebAPI project

0

Environment:

  • 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:

WebApiConfig.cs

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

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

}

Global.asax.cs

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

protected void Application_PostAuthorizeRequest()
{
    if (IsWebApiRequest())
    {
        HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
    }
}

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:

_Layout.cshtml

<body> @RenderBody()

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

@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); }) );

0

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.

0

Too many commands? Learning new language?

FavScripts.com 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 FavScripts.com!

Post Answer