简体   繁体   English

.NET Core WebAPI / Angular 项目 - 请求 header 字段内容类型在预检响应中不允许访问控制允许标头

[英].NET Core WebAPI / Angular project - Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response

I've been battling this issue now for around 30 hours, and I just cannot seem to get by it.我已经与这个问题斗争了大约 30 个小时,我似乎无法解决这个问题。 I'm having an issue with CORS in a .NET CORE 3.0.1 WebAPI project throwing the following error when called by my Angular project:我在 .NET CORE 3.0.1 WebAPI 项目中遇到 CORS 的问题,当我的 Angular 项目调用时抛出以下错误:

Access to XMLHttpRequest at ' http://localhost:4200/#/emailverified ' (redirected from ' http://localhost:5000/api/auth/forgotpassword ') from origin ' http://localhost:4200 ' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. Access to XMLHttpRequest at ' http://localhost:4200/#/emailverified ' (redirected from ' http://localhost:5000/api/auth/forgotpassword ') from origin ' http://localhost:4200 ' has been blocked通过 CORS 策略:请求 header 字段内容类型在预检响应中被 Access-Control-Allow-Headers 不允许。

I have CORS setup in my startup.cs file as follows:我的 startup.cs 文件中有 CORS 设置,如下所示:

ConfigureServices method in Startup.cs: Startup.cs 中的 ConfigureServices 方法:

services.AddCors(options => options.AddPolicy("CorsPolicy", p => p
                .WithOrigins("http://localhost:4200")
                .AllowAnyMethod()
                .WithHeaders("content-type")
                .AllowCredentials()
            ));

Configure method in Startup.cs:在 Startup.cs 中配置方法:

app.UseCors("CorsPolicy");

The API Call that is being made from the Angular service从 Angular 服务发出的 API 调用

resetpassword(model: any) {
    return this.http.post(this.baseUrl + 'forgotpassword', model);
  }

The controller: controller:

        [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");
        }

And lastly these are the headers being sent with the request:最后这些是与请求一起发送的标头:

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

I seriously cannot get past this and it is driving me absolutely nuts.我真的无法克服这一点,这让我非常抓狂。 Is there something I am missing here?我在这里缺少什么吗? I have added the "content-type" header to the CORS policy directly, but it just ignores it.我已将“内容类型”header 直接添加到 CORS 策略中,但它只是忽略了它。 I have searched high and low, and attempted about 2 dozen different ways of setting this up in my project.我搜索了高低,并在我的项目中尝试了大约 2 打不同的设置方法。 I've also tried clearing browser cache and using different browsers that have not been used on this project yet in case the cache was affecting it, and looking at the placement of app.UseCors("CorsPolicy") within the configure method, nothing seems to be getting this to work.我还尝试清除浏览器缓存并使用尚未在此项目中使用的其他浏览器,以防缓存影响它,并查看 app.UseCors("CorsPolicy") 在配置方法中的位置,似乎什么都没有让这个工作。

Is there something anyone can spot that I have missed?有没有人能发现我错过的东西?

CORS seems to work just fine everywhere else within the project except when using the following statement. CORS 似乎在项目中的其他任何地方都可以正常工作,除非使用以下语句。

return Redirect($"{_configuration["ViewUrl"]}/#/emailverified");

So after fighting with this for the better part of a week, I have decided not to use the redirect return statement in the controller and instead just let the front end angular project handle the redirect based off of the value of the return from he API.因此,在与这个问题斗争了一周的大部分时间之后,我决定不在 controller 中使用重定向返回语句,而是让前端 angular 项目根据来自他的 ZDB974238714CA86DEDZ 的返回值处理重定向。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 预检响应中的 Access-Control-Allow-Headers 不允许 ASP.Net WEB API 请求标头字段授权 - ASP.Net WEB API Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response Access-Control-Allow-Headers不允许请求标头字段x-user-session - Request header field x-user-session is not allowed by Access-Control-Allow-Headers ASP.NET Core Web API + Angular 对预检请求的响应未通过访问控制检查:预检请求不允许重定向 - ASP.NET Core Web API + Angular Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request Angular 6 - 对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头 - Angular 6 - Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header SEC7123:请求标头密钥不在Access-Control-Allow-Headers列表中 - SEC7123: Request header Key was not present in the Access-Control-Allow-Headers list 在 ASP.NET 中,对预检请求的响应未通过访问控制检查:No &#39;Access-Control-Allow-Origin&#39; 标头 - In ASP.NET, Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header .NET 5 对预检请求的响应未通过访问控制检查:没有'Access-Control-Allow-Origin' header 存在于请求的资源上 - .NET 5 Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource 内容类型-WebAPI-请求标头 - Content-Type - WebAPI - Request Header 在使用Wcf服务的Angular JS中的预检响应中,Access-Control-Allow-Methods不允许使用方法PUT - Method PUT is not allowed by Access-Control-Allow-Methods in preflight response in Angular JS With Wcf Service ASP.net核心信号器角度客户端,错误“对预检请求的响应未通过访问控制检查” - ASP.net core signalr angular client, error “Response to preflight request doesn't pass access control check”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM