我将Angular2与ASP.NET Core MVC一起使用并管理手动URL导航工作正常,服务器正在成功加载我的Home视图与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",我也得到了"设置&#34 ;当我的服务试图调用http.get时。 它似乎在方法的中间出错,因为我从未到达我在ASP控制器中设置的断点。我收到以下错误,我不明白:
"platform-browser.umd.js:937 EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property 'toString' of null"
可能是因为我不能在我的auth.guard中的适当时刻拨打电话吗?我的所有其他人都称之为使用http.post进行身份验证工作而没有任何问题,所以我不能真正解决问题的来源......
非常感谢任何帮助。
答案 0 :(得分:1)
Angular 2 RC5中有known defect,当您执行get
并提供'Content-Type': 'application/json'
标题时会导致此错误。
对于临时解决方法,请在请求选项的body
属性中添加一个空字符串:
let options = new RequestOptions({ headers: headers, body: "" });