【发布时间】:2025-12-10 15:05:02
【问题描述】:
我在这里发帖希望你们中的一个可以帮助我。我的编程知识很少,我被要求在 Angular 和 ASP.NET Core MVC 3 中构建一个简单的电子商务网站。因此,如果他/她是,以下代码应该不会将用户注销已登录但尝试通过 url 访问管理员页面。这是我的教授告诉我们使用的一些代码,但由于某种原因它对我不起作用。他使用的是旧版本的 Angular,例如,在他使用 .map() 的地方,我必须使用 .pipe(map()),而在他有 response.json().role 的地方,我只使用了 response.role。我的 IDE 在 response.authenticated 和 response.role 的客户端登录方法中显示以下错误
“boolean”类型上不存在“authenticated”(或“role”)属性。
我怀疑问题是在客户端登录方法上返回多个参数,或者它是由 .pipe(map()) 引起的。老实说,我在这里毫无头绪。我会很感激任何指导
登录:
login(): Observable<any> {
this.authenticated = false;
return this.repo.login(this.name, this.password).pipe(
map(response => {
if (response.authenticated == 'true') {
this.authenticated = true;
this.password = null;
this.role = response.role;
if (this.role == 'Administrator') {
this.router.navigateByUrl("/admin/overview");
this.admin = true;
}
else {
this.router.navigateByUrl("/");
}
}
return this.authenticated;
}),
catchError(e => {
this.authenticated = false;
return of(false);
})
);
}
服务器端登录:
[HttpPost("/api/account/login")]
public async Task<IActionResult> Login([FromBody] LoginViewModel creds) {
if (ModelState.IsValid && await DoLogin(creds)) {
IdentityUser user = await userManager.FindByNameAsync(creds.Name);
if (await userManager.IsInRoleAsync(user, "Administrator"))
return Ok(new { authenticated = "true", role = "Administrator"} );
else
return Ok( new { authenticated = "true", role = "NoAdministrator" });
}
return BadRequest();
}
【问题讨论】:
-
此外,您并没有像您声明的那样返回可观察对象。
标签: javascript asp.net angular typescript asp.net-mvc-3