【问题标题】:No 'Access-Control-Allow-Origin' header is present Angular 6 with Asp.net Core 2.1Angular 6 与 Asp.net Core 2.1 不存在“Access-Control-Allow-Origin”标头
【发布时间】:2019-01-12 10:15:46
【问题描述】:

不断收到 No 'Access-Control-Allow-Origin' header is present 使用 asp.net core 2.1 的角度 6 中的错误。

我知道这是 cors 错误。我已经在服务器端添加了策略,但仍然是同样的问题。

startup.cs

services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader()
                       .AllowCredentials().WithOrigins("http://localhost:4200");
            }));



app.UseCors("CorsPolicy");

app.UseMvc();

控制器代码

[HttpPost, AllowAnonymous]
        public GenericResponseObject<JwtTokenViewModel> UserAuthentication([FromBody] UserViewModel user)
        {

            GenericResponseObject<JwtTokenViewModel> genericResponseObject = new GenericResponseObject<JwtTokenViewModel>();
            genericResponseObject.IsSuccess = false;
            genericResponseObject.Message = ConstaintStingValue.TagConnectionFailed;
            if (ModelState.IsValid)
            {
                try
                {
                    UserViewModel userViewModel = _adminUOW.AdminAuthentication(user);
                    if (userViewModel != null)
                    {
                        string token = new CommonController(tokenOptions).GetToken(userViewModel, DateTime.UtcNow.AddDays(2));
                        genericResponseObject.Data = new JwtTokenViewModel
                        {
                            UserName = userViewModel.UserName,
                            UserId = userViewModel.UserId,
                            authenticated = true,
                            entityId = 1,
                            tokenExpires = DateTime.UtcNow.AddHours(2),
                            token = token,
                            SelectedRole = userViewModel.SelectedRole
                        };
                    }
                    else
                    {
                        genericResponseObject.SuccessMessage = ConstaintStingValue.Tag_No_Profile_key;
                    }

                    genericResponseObject.IsSuccess = true;
                    genericResponseObject.Message = ConstaintStingValue.TagConnectionSuccess;
                }
                catch (Exception exception)
                {
                    genericResponseObject.IsSuccess = true;
                    genericResponseObject.SuccessMessage = exception.Message;
                    genericResponseObject.ErrorCode = exception.HResult;
                    genericResponseObject.ExceptionErrorMessage = exception.StackTrace;
                    WriteExceptionToFile.WriteExceptionToFileInLogger(_hostingEnvironment, exception);
                }
            }

            return genericResponseObject;

        }

打字稿代码

login(modelValue: UserViewModel, isValid: boolean) {
    if (isValid) {   this.genericHttpClientService.GenericHttpPostAndResponse<GenericResponseObject<JwtTokenViewModel>, UserViewModel>(this._userViewModel, this.commonConstantValue.adminLoginUrl).subscribe(item => {
                if (item.data!= null && item.data.authenticated) {
                  this.router.navigate(['admin-portal']);
                }else{
                  this.genericViewModel.successMessage = item.successMessage;
                }
                this.progressBarDisplay = false;
            },
            err => {
                console.log(err);
                this.progressBarDisplay = false;
            });

    }

HttpCLient

public GenericHttpPostAndResponse<T,TE>(postViewModel: TE, destinationUrl: string): Observable<T> {
    const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
    return this.httpClientModule.post<T>(environment.baseUrl + destinationUrl, postViewModel, { headers });
}

Getting Error " No 'Access-Control-Allow-Origin' header is present on the requested resource." in ionic2

How to enable CORS in ASP.net Core WebAPI

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1

【问题讨论】:

  • 你能分享你的api代码吗?
  • 添加控制器代码.....
  • 你为 5001 端口设置 HTTPS 了吗?
  • 对于令牌请求,不需要来自正文。此外,您应该提供内容类型:application/x-www-form-urlencoded
  • 注意AllowAnyOrigin()会清空origins列表,然后将*添加到origins,后面的WithOrigins会添加"http://localhost:4200"到origins列表。所以,WithOriginsAllowAnyOrigin 之后是不必要的,可能是你的问题的原因。

标签: c# asp.net angular typescript asp.net-core


【解决方案1】:

很难说真正的问题是什么。我对 CORS 的经验是,它在实践中比人们想象的要难。我有一个类似的问题,这是由于我的网站需要 Windows 身份验证。结果是预检 CORS 请求需要匿名身份验证。我看到您的控制器具有 AllowAnonymous 属性,但是,如果它托管在 IIS 中,那么该站点也需要具有匿名身份验证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 2018-10-28
    • 2017-04-15
    • 2018-05-16
    相关资源
    最近更新 更多