HttpContext.Current is null in the WebAPI project

0
=
0
+
0
No specific Bitcoin Bounty has been announced by author. Still, anyone could send Bitcoin Tips to those who provide a good answer.
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

2
=
0
=
$0
Internet users could send Bitcoin Tips to you if they like your answer!

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

SEND BITCOIN TIPS
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.

SEND BITCOIN TIPS
0

Too many commands? Learning new syntax?

FavScripts.com is a free tool to save your favorite scripts and commands, then quickly find and copy-paste your commands with just few clicks.

Boost your productivity with FavScripts.com!

Post Answer