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 - total earned - 0 BTC ($0 USD)

2
=
0
=
$0
Everyone, even non-registered users could send Bitcoin Tips to YOU if they are inspired by 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

Post Answer


Top 3 Tippers
Recent Tips

Will Bitcoin Tipping become a new Internet Culture?


Please share our story! THANK YOU!