.NET CORE 2.0 Angular 5:允许Cors

Ben*_*lly 4 cors asp.net-core angular

我在使用cors时遇到了一些麻烦。我设置为server side

  app.UseCors(builder => builder.WithOrigins("http://localhost:4200/").AllowAnyHeader());
Run Code Online (Sandbox Code Playgroud)

在里面configure的方法startup

当点击我的Web API时,它将返回数据。

但是,问题似乎出在Angular上,因为出现以下错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)

这是我的角度网络API调用

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';;


@Injectable()
export class ProfileService {

    private baseUrl = 'api/profile/';

    constructor(private http: HttpClient) { }

    getLookups(step: number) {
        return this.http.get('http://localhost:51658/' + this.baseUrl + 'lookups/' + step)
    }

}
Run Code Online (Sandbox Code Playgroud)

Ben*_*lly 15

改变builder.WithOrigins("http://localhost:4200/")

builder.WithOrigins("http://localhost:4200")
Run Code Online (Sandbox Code Playgroud)

(去掉了“/”)


小智 9

使用以下命令更改API中的行:

app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowAnyCredentials());
Run Code Online (Sandbox Code Playgroud)

请确保您添加Services.AddCors();到ConfigureServices()中,然后停止服务器并在进行更改后再次运行。

  • 重复代码后出现异常。-- System.InvalidOperationException: 'CORS 协议不允许同时指定通配符(任何)来源和凭据。如果需要支持凭据,请通过列出各个来源来配置 CORS 策略。-- 删除 .AllowCredentials 帮助了我 (3认同)
  • @JamesPoulose应该只是.AllowCredentials() (2认同)

Pav*_*nov 5

“ WithOrigins”期望一个数组,而不是一个字符串,所以也许是您的情况。但是,在您的情况下,Cors起作用的最低要求是:

在Startup.cs加入 services.AddCors();之前services.AddMvc(); ,也:

string[] origins = new string[] { "http://localhost:4200" }; app.UseCors(b=>b.AllowAnyMethod().AllowAnyHeader().WithOrigins(origins));

再次添加之前 app.UseMvc(your routes ...)

或您实际需要的技术无关紧要,就是在服务器的响应中添加“ Access-Control-Allow-Origin”标头,并将其值作为起点/起点,在.Net core 2中可以这样完成(在控制器中的任何方法):
ControllerContext.HttpContext .Response .Headers .Add("Access-Control-Allow-Origin","http://localhost:4200");

或全局-您可以创建一个中间件,以在原点匹配时将此标头添加到所有响应中。在Angular 6和.Net Core 2中也可以作为单独的应用程序使用。

  • `WithOrigins` 需要一个 `params string[]` - 这意味着多个单独的字符串参数。单个 `string` 参数完全没问题。 (2认同)