在web api的每个请求中都创建了一个新会话
我正在用AngularJS开发ASPN.NET WEB API 1(使用.NET Framework 4.0)应用程序,并且我正在使用会话来验证用户(我知道它应该无国籍,但为了遗留目的,我正在使用会话)。在我的应用程序中,每次向我的WEB API发出请求时,都会创建一个新的会话,即使我为会话设置了值。在web api的每个请求中都创建了一个新会话
的会话是允许在我的器件的应用,通过这个代码在Global.asax中:
protected void Application_BeginRequest(object sender, EventArgs e) {
string origins = ConfigurationManager.AppSettings["cors-origins"];
bool hasSlash = origins.Substring(origins.Length - 1, 1) == "/";
if (hasSlash)
origins = origins.Substring(0, origins.Length - 1);
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origins);
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
"Content-Type, Accept");
HttpContext.Current.Response.End();
}
}
protected void Application_PostAuthorizeRequest()
{
if (IsWebApiRequest())
{
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
}
然后我设定值,我会在我的控制器:
public HttpResponseMessage Post(LoginViewModel model) {
// SOME BUSINESS LOGIC HERE...
FormsAuthentication.SetAuthCookie(model.User, false);
HttpContext.Current.Session["usuario"] = model.User;
return Request.CreateResponse(HttpStatusCode.Accepted, "User successfylly logged in!");
}
但是,当我做的另一个请求我的应用程序访问控制器中的另一种方法,它会抛出一个错误,因为会话为空,就像在此方法中一样:
public HttpResponseMessage Get() {
var userName = HttpContext.Current.Session["usuario"];
return Request.CreateResponse(HttpStatusCode.Accepted, userName);
}
在我的web.config,会话配置是这样的:
<sessionState mode="InProc" customProvider="DefaultSessionProvider" > <providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
PS:它无法在Chrome工作,但在IE上它的工作原理,并直接在邮递员它也可以做的请求。
回答:
它缺少这一行我Application_BeginRequest
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
并在AngularJS每个请求我应该通过withCredentials参数为真。为了实现这一目标,我把这个线在我的配置文件在AngularJS:
$httpProvider.defaults.withCredentials = true;
以上是 在web api的每个请求中都创建了一个新会话 的全部内容, 来源链接: utcz.com/qa/263337.html