在手动 URL 导航上管理用户身份验证状态

Managing user authenticated state on manual URL navigation

我将 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",我也得到了 "Setting Up"当我的服务尝试调用 http.get 时。 它似乎在方法中间出现错误,因为我从来没有到达我在 ASP 控制器中设置的断点。我收到以下我不明白的错误:

"platform-browser.umd.js:937 EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property 'toString' of null"

可能是因为我没有在 auth.guard 中的正确时刻调用该服务?我的所有其他调用(例如身份验证)都可以与 http.post 一起使用,没有任何问题,所以我真的不知道问题出在哪里...

如有任何帮助,我们将不胜感激。

Angular 2 RC5 中有一个 known defect,当您执行 get 并提供 'Content-Type': 'application/json' header.[=15 时会导致此错误=]

对于临时解决方法,请将空字符串添加到请求选项的 body 属性 中:

let options = new RequestOptions({ headers: headers, body: "" });