【发布时间】:2014-07-25 16:07:10
【问题描述】:
我的应用程序向 API 控制器发出大量请求。我遇到的问题是我的 APIController 无法访问当前会话(它不应该)。但由于调用是在页面加载后通过 javascript 进行的 - 我不知道如何告诉我的应用程序更新会话。
在接收到来自 ajax 调用的更新数据后,处理会话值更改的公认方法是什么?
例子:
public static class SessionManager
{
public static User CurrentUser
{
get
{
return (User)HttpContext.Current.Session["CurrentUser"];
}
set
{
HttpContext.Current.Session["CurrentUser"] = value;
}
}
}
public class SomeController : ApiController
{
public HttpResponseMessage DeleteSomething(SomeModel model)
{
// Do work
}
}
然后在视图中
$.ajax({
type: 'DELETE',
url: '{PATH TO API}',
data: { the data },
traditional: true,
success: function (response) {
// Now I need to update the user stored in the session
// How do I do that?
} else {
}
});
【问题讨论】:
-
为什么不能像在 SessionManager 中那样使用 HttpContext.Current.Session?
-
@JasonGoemaat 我试过了 - 但它似乎不起作用。我添加了一个断点,当从 API 控制器引用时,“CurrentUaer”似乎为空。
-
您可以访问
User属性并使用内置安全性吗?您可以通过用户名而不是会话将User对象存储在 HttpCache 中... -
@JasonGoemaat:这是一个 Web API。它是无状态的。没有会话,没有缓存。每个请求就像您以前从未与之交互过一样。获得“用户”的唯一方法是在请求中传递身份验证令牌。
-
@ChrisPratt 不会来自同一站点上的页面的 AJAX 调用发送相同的 http 请求信息吗? (page) - 哦,我知道他想更新会话。可以创建自己的 HTTP 处理程序来为您提供会话,但是是的,这可能是不可取的。
标签: c# asp.net ajax asp.net-mvc asp.net-mvc-4