要解决Angular 7 .net core 2.2 WebApi Windows Authentication CORS的问题,你可以按照以下步骤进行操作:
@angular/common
和@angular/http
模块:npm install @angular/common @angular/http
auth.interceptor.ts
的新文件,并将以下代码复制到该文件中:import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(request: HttpRequest, next: HttpHandler): Observable> {
// 将认证信息添加到请求头中
request = request.clone({
withCredentials: true
});
return next.handle(request);
}
}
app.module.ts
文件中,将AuthInterceptor
添加到providers
数组中:import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth.interceptor';
@NgModule({
...
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
],
...
})
export class AppModule { }
Startup.cs
文件,并在ConfigureServices
方法中添加以下代码:services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc();
Configure
方法中,将以下代码添加到app.UseMvc
之前:app.UseCors("AllowAll");
app.UseAuthentication();
这样就完成了Angular 7 .net core 2.2 WebApi Windows Authentication CORS的设置。在进行跨域请求时,认证信息将被正确地发送到后端API。