访问会话使用的ASP.NET Web API [英] Accessing Session Using ASP.NET Web API
问题描述
我认识会话和REST不完全齐头并进,但它是不可能使用新的Web API来访问会话状态? HttpContext.Current.Session
总是空。
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.
推荐答案
我目前使用MVC4这个解决方案,它的工作很好:
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);
}
}
此解决方案的好处,我们可以在javascript中获取基URL使得AJAX调用:
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)
然后我们的JavaScript文件/ code之内,我们可以使我们的WebAPI调用,可以访问会话:
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);
})
);
唷!
这篇关于访问会话使用的ASP.NET Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!