在Net Core api项目中的Startup.cs文件中添加以下代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
//其他代码
}
然后,在Net Core api控制器类中,使用[EnableCors]特性并指定策略名称:
[EnableCors("AllowAllOrigins")]
public class YourController : ControllerBase
{
//其他代码
}
最后,在Angular应用程序中,使用HttpClient模块时,在请求头中添加以下代码:
import { HttpClient, HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PATCH, DELETE, PUT, OPTIONS'
})
};
@Injectable()
export class YourService {
constructor(private http: HttpClient) {
}
yourFunction() {
return this.http.get('https://your-net-core-api-url', httpOptions)
.pipe(map(res => res.json()));
}
}