如何将Angular 10登录应用与含PostgreSQL连接的C#后端对接
实现从PostgreSQL验证登录并完成Angular与ASP.NET Core对接
第一步:完善ASP.NET Core后端,添加登录验证API接口
你已经基于EF Core搭建了PostgreSQL的连接上下文,接下来需要补充API层来处理前端的登录请求:
1. 创建登录数据传输类(DTO)
在Model项目里新增用于前后端数据交互的类:
namespace Model { // 接收前端登录请求的参数 public class LoginRequestDto { public string UserID { get; set; } public string Password { get; set; } public string SelectedRole { get; set; } } // 返回给前端的登录结果 public class LoginResponseDto { public bool IsAuthenticated { get; set; } public string RedirectUrl { get; set; } } }
2. 编写认证API控制器
在ASP.NET Core项目中创建AuthController,实现数据库验证逻辑:
using Microsoft.AspNetCore.Mvc; using Model; using System.Linq; namespace YourAspNetProject.Controllers { [ApiController] [Route("api/[controller]")] public class AuthController : ControllerBase { private readonly UserContext _dbContext; // 通过构造函数注入数据库上下文 public AuthController(UserContext dbContext) { _dbContext = dbContext; } [HttpPost("login")] public IActionResult Login([FromBody] LoginRequestDto request) { bool isValid = false; string redirectUrl = string.Empty; // 根据角色查询对应表的用户信息 if (request.SelectedRole == "User") { var employee = _dbContext.Employees.FirstOrDefault(e => e.UserID == request.UserID && e.Password == request.Password); isValid = employee != null; redirectUrl = isValid ? "/userpage" : string.Empty; } else if (request.SelectedRole == "Admin") { var admin = _dbContext.Admins.FirstOrDefault(a => a.UserID == request.UserID && a.Password == request.Password); isValid = admin != null; redirectUrl = isValid ? "/adminpage" : string.Empty; } return Ok(new LoginResponseDto { IsAuthenticated = isValid, RedirectUrl = redirectUrl }); } } }
重要提醒:上面的代码是为了快速演示直接对比明文密码,实际生产环境必须使用哈希密码(比如借助
BCrypt或ASP.NET Core Identity的密码哈希工具),绝对不能存储明文密码!
3. 配置跨域(CORS)
因为Angular和ASP.NET Core默认运行在不同端口,需要允许前端跨域访问后端API:
- 如果你用的是.NET 6+,在
Program.cs中添加:
builder.Services.AddCors(options => { options.AddPolicy("AllowAngular", policy => policy.WithOrigins("http://localhost:4200") // Angular默认启动端口 .AllowAnyHeader() .AllowAnyMethod()); }); // 在app.UseRouting()之后添加 app.UseCors("AllowAngular");
第二步:修改Angular前端,调用后端API替代模拟验证
1. 引入HTTP模块
先确保Angular项目中启用了HttpClientModule,在app.module.ts中添加:
import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ // 其他已导入模块 HttpClientModule ] }) export class AppModule { }
2. 更新登录认证服务,替换为API请求
修改loginauthentication.service.ts,用HTTP请求替代模拟数据验证:
import { Injectable } from '@angular/core'; import { SignInData } from 'src/SignInData'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class LoginauthenticationService { // 替换成你的ASP.NET Core API实际地址 private apiBaseUrl = 'https://localhost:5001/api/Auth'; isAuthenticated = false; constructor(private http: HttpClient) { } // 返回Observable让组件处理异步响应 Authenticate(signInData: SignInData, selectedRole: string): Observable<any> { const loginPayload = { userID: signInData.getUserID(), password: signInData.getPassword(), selectedRole: selectedRole }; return this.http.post(`${this.apiBaseUrl}/login`, loginPayload); } }
3. 修改登录组件,处理API响应
更新login.component.ts中的Login方法,改为异步处理API返回结果:
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { LoginauthenticationService } from "../loginauthentication.service"; import { SignInData } from 'src/SignInData'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { constructor(private router: Router, private loginAuthenticationService: LoginauthenticationService) { } ngOnInit(): void { } alertmessage = false; selectedRole = 'User'; userID = ''; password = ''; RoleSelection(role: string) { this.selectedRole = role; } Login() { const logindata = new SignInData(this.userID, this.password); // 订阅API请求的响应 this.loginAuthenticationService.Authenticate(logindata, this.selectedRole).subscribe( (response) => { if (response.isAuthenticated) { this.loginAuthenticationService.isAuthenticated = true; this.router.navigate([response.redirectUrl]); } else { this.alertmessage = true; } }, (error) => { console.error('登录请求出错:', error); this.alertmessage = true; } ); } GoToRegistration() { this.router.navigate(['/registration']); } }
第三步:验证完整流程
- 确保PostgreSQL的
UserDB数据库中,Employees和Admins表已存在并插入测试数据(比如user1/123、admin1/456); - 启动ASP.NET Core后端项目;
- 启动Angular项目(运行
ng serve); - 在登录页面输入对应账号密码和角色,验证是否能正确跳转,错误信息是否正常显示。
进阶建议:实际项目中推荐使用JWT令牌进行身份认证,后端生成JWT返回给前端,前端存储令牌后,后续请求携带令牌完成权限验证,这样比单纯的状态标记更安全可靠。
内容的提问来源于stack exchange,提问作者Ninini
相关产品推荐
相关产品推荐

