在Angular和ASP.NET Core 2.1中解决CORS问题的一种方法是通过配置ASP.NET Core的Startup.cs文件来启用CORS。
首先,在ASP.NET Core的Startup.cs文件中添加以下代码来配置CORS:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAngular", builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("AllowAngular");
app.UseMvc();
}
在上述代码中,我们创建了一个名为“AllowAngular”的CORS策略,并在WithOrigins方法中指定了Angular应用的URL(在这个例子中,假设Angular应用运行在http://localhost:4200)。我们还使用AllowAnyHeader和AllowAnyMethod方法来允许任何请求头和请求方法。
接下来,在Angular应用中,我们需要使用Angular的HttpClient来发送跨域请求。在发送请求之前,需要在请求头中添加“Access-Control-Allow-Origin”字段,以便服务器能够接受来自不同域的请求。
在Angular的组件或服务中,可以使用以下代码来发送跨域请求:
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) { }
sendRequest() {
const url = 'http://localhost:5000/api/example'; // ASP.NET Core API的URL
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://localhost:4200' // Angular应用的URL
};
this.http.get(url, { headers }).subscribe(response => {
console.log(response);
});
}
在上述代码中,我们在请求头中添加了“Access-Control-Allow-Origin”字段,以使服务器能够接受来自Angular应用的请求。
通过以上配置和代码,您应该能够在Angular应用中发送跨域请求到ASP.NET Core 2.1的API,并成功解决CORS问题。