c# - .NET Core WebAPI / Angular 项目 - 预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段内容类型
问题描述
我已经与这个问题斗争了大约 30 个小时,我似乎无法解决这个问题。我在 .NET CORE 3.0.1 WebAPI 项目中遇到 CORS 问题,当我的 Angular 项目调用时抛出以下错误:
从源“ http ://localhost:4200 ”访问“ http://localhost:4200/#/emailverified ”(从“ http://localhost:5000/api/auth/forgotpassword ”重定向)的XMLHttpRequest已被阻止通过 CORS 策略:在预检响应中 Access-Control-Allow-Headers 不允许请求标头字段内容类型。
我的 startup.cs 文件中有 CORS 设置,如下所示:
Startup.cs 中的 ConfigureServices 方法:
services.AddCors(options => options.AddPolicy("CorsPolicy", p => p
.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.WithHeaders("content-type")
.AllowCredentials()
));
在 Startup.cs 中配置方法:
app.UseCors("CorsPolicy");
从 Angular 服务进行的 API 调用
resetpassword(model: any) {
return this.http.post(this.baseUrl + 'forgotpassword', model);
}
控制器:
[AllowAnonymous]
[EnableCors("CorsPolicy")]
[HttpPost("forgotpassword")]
public async Task<IActionResult> ForgotPassword(SendPasswordResetDto sendPasswordReset)
{
if (sendPasswordReset.Email == null)
{
return NotFound("Please enter a valid email address");
}
var user = await _userManager.FindByEmailAsync(sendPasswordReset.Email);
// If the email does not exist, return null
if (user == null)
{
return Redirect($"{_configuration["ViewUrl"]}/#/emailverified");
}
// If the user email does exist, create a password reset token and encode it in a browser friendly way
var forgotPasswordToken = await _userManager.GeneratePasswordResetTokenAsync(user);
var encodedToken = Encoding.UTF8.GetBytes(forgotPasswordToken);
var validToken = WebEncoders.Base64UrlEncode(encodedToken);
// Send an email to the user with the reset email link
string url = $"{_configuration["ViewUrl"]}/#/changepassword?email={user.Email}&token={validToken}";
await _MailRepository.SendEmailAsync(user.Email, "Password Reset", $"<h1>You have requested to reset your password.</h1> <p>Please click <a herf='{url}'>this link</a> to reset your password. If it does not work, please copy and paste this link into your browser " + url + "</p>");
return Redirect($"{_configuration["ViewUrl"]}/#/emailverified");
}
最后这些是与请求一起发送的标头:
Request URL: http://localhost:4200/
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: 127.0.0.1:4200
Referrer Policy: no-referrer-when-downgrade
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:5000
Origin: http://localhost:4200
Pragma: no-cache
Referer: http://localhost:4200/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36
我真的无法克服这一点,这让我非常抓狂。我在这里缺少什么吗?我已将“内容类型”标头直接添加到 CORS 策略中,但它只是忽略了它。我搜索了高低,并在我的项目中尝试了大约 2 打不同的设置方法。我还尝试清除浏览器缓存并使用尚未在此项目中使用的不同浏览器,以防缓存影响它,并查看 app.UseCors("CorsPolicy") 在 configure 方法中的位置,似乎没有让这个工作。
有没有人能发现我错过的东西?
解决方案
除了使用以下语句时,CORS 似乎在项目中的其他任何地方都可以正常工作。
return Redirect($"{_configuration["ViewUrl"]}/#/emailverified");
因此,在与这个问题斗争了一周的大部分时间之后,我决定不在控制器中使用重定向返回语句,而是让前端 Angular 项目根据来自他的 API 的返回值来处理重定向。
推荐阅读
- reactjs - React Final Form Material UI 在输入字段上创建双线
- c# - 以 AA、AB、AC 等形式显示 PDF 中记录列表的索引
- docker - 有没有办法在特定目录中安装 docker 映像的所有包?
- mysql - 同步 MySql Server 和 VB.Net Winform 应用程序
- git - 我需要在合并之前在本地拉 PR
- ios - 在 iPhone 12 中安装 IPA 时出错(错误域 = NSPOSIXErrorDomain 代码 = 2)
- javascript - REGEX - 匹配长字符串中的模式
- vba - 创建计算字段时应用程序定义或对象定义错误
- html - Bootstrap 4 单选框和复选框样式
- java - 检查 JSONObject 是否匹配 JSON 布尔表达式