在ASP.net core中创建一个Web API后端,并在其Startup.cs文件中启用CORS。
在Angular应用程序中创建一个新模块,并将此模块添加到AppModule中。
在Angular中使用HttpClient服务从后端API获取数据。
在Angular中使用路由模块来指定应用程序的不同视图和URL。可以使用路由守卫来保护一些页面或检查用户的权限。
以下是一些示例代码:
在ASP.net core中设置CORS:
public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); }
public void Configure(IApplicationBuilder app) { app.UseCors("CorsPolicy"); // other configurations }
在Angular中创建新的模块:
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule, RouterModule.forRoot([ { path: '', component: HomeComponent }, { path: 'products', component: ProductsListComponent }, { path: 'product/:id', component: ProductDetailComponent } ]), ], providers: [ProductsService], bootstrap: [AppComponent] }) export class AppModule { }
从后端API获取数据:
@Injectable() export class ProductsService {
private apiUrl = 'https://localhost:5001/api/products';
constructor(private http: HttpClient) { }
getProducts(): Observable
getProduct(id: number): Observable${this.apiUrl}/${id}
);
}
}
在Angular中使用AuthGuard路由守卫:
@Injectable() export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { if (this.authService.isLoggedIn()) { return true; }
this.router.navigate(['/login']);
return false;
} }
RouterModule.forRoot([ { path: '', component: HomeComponent }, { path: 'products', component: ProductsListComponent, canActivate:
上一篇:ASP.NETCore与Winforms-保存用户名一次
下一篇:ASP.NETCore在部署到IIS上时,HttpContext.Session.Clear()方法不能正确清除Session会话。