我将 Angular2 与 ASP.NET Core MVC 结合使用,并且管理手动 URL 导航工作正常,服务器正在使用 Angular2 成功加载我的主页视图。
在用户身份验证上,我设置一个会话变量,如下所示:
HttpHelper.HttpContext.Session.SetString("isLoggedIn", true.ToString() );
我想要的是,在用户进入应用程序后,如果他想通过手动导航来加载特定路由,我希望我的服务调用我的 ASP 控制器来检查用户是否已经通过身份验证,以便我的警卫允许路由。相反,守卫默认设置为 false,我显然会被重定向到我的登录页面。
这是我的 ASP 控制器方法,我想调用它来更新 auth.service 中的 IsLoggedIn 值:
[HttpGet]
public IActionResult IsConnectedState()
{
if (!String.IsNullOrWhiteSpace(HttpHelper.HttpContext.Session.GetString("isLoggedIn")))
return Ok(true);
else
return Ok(false);
}
这样我的 AuthenticationGuard 可以调用 AuthenticationService 来更新管理已验证状态的布尔值:
alert(this.authService.isLoggedIn);
if (!this.authService.isLoggedIn) {
this.authService.setupLoggedInState().subscribe(() => { });
}
使用以下代码更新我的 auth.service 中的布尔值:
setupLoggedInState() {
alert("Setting Up");
// Setting up the Http call
let lControllerAction: string = "/IsConnectedState";
let lControllerFullURL: string = this.controllerURL + lControllerAction;
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
// Call my ASP Controller IsConnectedState() method
return this.http.get(lControllerFullURL, options)
.map((res: any) => {
// Réponse reçue du WebService
let data = res.json();
alert(data);
if (data == true) {
this.isLoggedIn = true;
}
}
).catch(this.handleError);
}
当我进行身份验证,然后手动导航到 URL 时,我的守卫告诉我布尔值确实设置为“false”,并且当我的服务尝试调用 http.get 时,我也会得到“Setting Up”。
它似乎在方法中间出现错误,因为我从未到达在 ASP 控制器中设置的断点。我收到以下我不明白的错误:
"platform-browser.umd.js:937 EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property 'toString' of null"
难道是因为我没有在 auth.guard 中的正确时刻调用该服务?我所有其他人都打电话,例如使用 http.post 进行身份验证,没有任何问题,所以我真的不明白问题来自哪里......
任何帮助将不胜感激。