CORS策略已阻止从源本地主机4200访问Angular 9和.NET Core
我在Angular 9中有应用程序,在.NET Core 3.1中有后端 当我想从angular client发出请求时:CORS策略已阻止从源本地主机4200访问Angular 9和.NET Core,angular,asp.net-core-mvc,cors,Angular,Asp.net Core Mvc,Cors,我在Angular 9中有应用程序,在.NET Core 3.1中有后端 当我想从angular client发出请求时: private httpHeaders: HttpHeaders; constructor(private httpClient: HttpClient, @Inject('BASE_URL') private baseUrl: string) { this.httpHeaders = new HttpHeaders({ 'Access-Contr
private httpHeaders: HttpHeaders;
constructor(private httpClient: HttpClient, @Inject('BASE_URL') private baseUrl: string) {
this.httpHeaders = new HttpHeaders({
'Access-Control-Allow-Origin': '*'
});
}
return this.httpClient.get<any>(`${environment.apiUrl}/findUser/GetUsers?name=${name}&lastname=${lastname}`, {
headers: this.httpHeaders,
reportProgress: true,
observe: 'events'
});
在控制器中:
[HttpGet]
[Route("getUsers")]
public IEnumerable<UserAccountDTO> GetUsers(string name, string lastname)
{}
这是一项请求:
GET /findUser/GetUsers?name=&lastname= HTTP/1.1
Host: localhost:20677
Connection: keep-alive
Access-Control-Allow-Origin: *
Accept: application/json
Authorization: Bearer xxxxxxxxxxxxxxx
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36
Content-Type: application/json
Origin: http://localhost:4200
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: http://localhost:4200/find-user
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
使用代理文件,创建
proxy.config.json
{
"/api/*": {
"target": "http://localhost:20677/api",
"pathRewrite": {
"^/api": ""
},
"changeOrigin": true,
"secure": false,
"logLevel": "debug"
}
}
并与
ng serve --proxy-config proxy.config.json
你似乎对CORS的理解是错误的;我看到您的客户端代码在其请求中添加了一个CORS头,但这就是它的工作方式
- 浏览器知道从何处下载应用程序(http://localhost:4200)
- 浏览器知道应用程序从何处请求数据(http://localhost:20677/findUser/GetUsers? name=&lastname=John)
- 浏览器会看到这些是不同的
- 在浏览器对代码的请求执行操作之前,获取/发布/任何内容到
它首先发出一个单独的请求http://localhost:20677/findUser/GetUsers? name=&lastname=John
发送到服务器:4200选项http://localhost:20677/findUser/GetUsers? name=&lastname=John
- 这就像是在说“嘿,20677,这个应用程序是其他网站为我提供的,它试图从你那里获取数据。你允许世界上哪些网站这样做?”
- 如果20677的网站上说“我们允许4200”或“我们允许任何”,那么请求就会成功。如果站点说了其他内容,或者什么都没有(选项响应中没有访问控制允许源标题),那么浏览器平面拒绝执行代码想要执行的GET/POST/ETC
//在ConfigureServices中
public void配置服务(IServiceCollection服务)
{
services.AddCors(选项=>
{
options.AddPolicy(
名称:“AllowOrigin”,
生成器=>{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
}
//在配置中
公共void配置(IApplicationBuilder应用程序)
{
附录UseCors(“AllowOrigin”);
}
注意:我在收到ok后更新了答案;我在UseCors中漏掉了一个双引号
于2021年4月17日更新
app.UseCors(“AllowOrigin”)
必须位于其他中间件的顶部。我在几个项目中使用过它,它对我来说非常适合
注意:此代码位于Startup.cs中的statUp.cs中,我添加了:
services.AddCors();
及
app.UseRouting();
app.UseCors(x=>x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
//附录UseCors(“AllowOrigin”);
//自定义jwt身份验证中间件
app.UseMiddleware();
我有两个控制器:
WheaterController generated by Visual Studio:
[EnableCors()]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
[Route("getwheater")]
public IEnumerable<WeatherForecast> Get()
{
}
}
WheaterController由Visual Studio生成:
[EnableCors()]
[ApiController]
[路线(“[控制器]”)]
公共类WeatherForecastController:ControllerBase
{
[HttpGet]
[路线(“getwheater”)]
公共IEnumerable Get()
{
}
}
和由我的创建的控制器:
[EnableCors()]
[ApiController]
[Route("[controller]")]
public class FindUserController : ControllerBase
{
[HttpGet]
[Route("getusers2")]
public IEnumerable<UserAccountDTO> GetUsers2()
{
return new List<UserAccountDTO>();
}
}
[EnableCors()]
[ApiController]
[路线(“[控制器]”)]
公共类FindUserController:ControllerBase
{
[HttpGet]
[路由(“getusers2”)]
公共IEnumerable GetUsers2()
{
返回新列表();
}
}
当我从Angular调用request到WheaterController时,它工作了,但当我调用FindUserController时,我出现了如上所述的错误:cors等。
两个控制器之间的区别是什么
现在我知道问题出在哪里了。 在构造函数中,我有一个未添加到依赖项注入的Startup.cs中的接口,Visual向我显示了类似CORS的错误 感谢您的帮助。步骤:
Microsoft.AspNetCore.Cors
ConfigureServices
services.AddCors();
Configure
app.UseCors(x => x.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true) // allow any origin
.AllowCredentials());
我添加了proxy.config.json,内容如上所述,我有相同的错误。我的服务器地址是,不是,我应该从地址中删除api?如果api在根目录中,部署它时,您将如何托管它?它将与网站托管冲突。如果它解决了您的问题,请接受答案。谢谢
WheaterController generated by Visual Studio:
[EnableCors()]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
[Route("getwheater")]
public IEnumerable<WeatherForecast> Get()
{
}
}
[EnableCors()]
[ApiController]
[Route("[controller]")]
public class FindUserController : ControllerBase
{
[HttpGet]
[Route("getusers2")]
public IEnumerable<UserAccountDTO> GetUsers2()
{
return new List<UserAccountDTO>();
}
}
services.AddCors();
app.UseCors(x => x.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true) // allow any origin
.AllowCredentials());