1
我正在用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上它的工作原理,并直接在邮递员它也可以做的请求。
当你建立一个API,每个请求都是独立的,无论在什么方面,以任何过去或未来的请求没有任何关系。你不是在这里建立一个Web应用程序。如果您想知道谁在发送请求,请查看身份验证机制,例如oauth或您认为合适的任何其他身份验证机制。只要不要像一个网络应用程序对待一个API,这里没有传统的借口。 –