我们可以使用一个代理来解决这个问题。在Angular的proxy.conf.json文件中,我们将目标服务的URL设置为API服务的URL,如下所示:
{
"/api/*": {
"target": "https://localhost:5001",
"secure": false
}
}
然后,在Angular的环境文件中,我们做如下设置:
export const environment = {
production: false,
apiUrl: '/api'
};
在我们的Angular服务中,我们可以这样调用API:
private apiUrl = environment.apiUrl;
public getCustomers(): Observable {
return this.http.get(`${this.apiUrl}/customers`);
}
在API的Startup.cs文件中,我们需要添加以下代码,以允许跨域访问:
services.AddCors();
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
这样我们就解决了Asp.Net Webapp和Asp.Net Core Api之间的连接问题。
上一篇:ASP.NETCoreAPI与Angular端读取流的问题,EventSource的响应具有MIME类型(“application/json”),但不是“text/event-stream”。