从CORS策略阻止从源“ http:// localhost:4200”访问“ URL”处的XMLHttpRequest:

时间:2020-06-22 13:57:04

标签: c# asp.net-core-webapi asp.net-core-3.1

我以为我可以访问所有来源,但仍然出现此错误。

从源访问“ localhost:60248 / api / page / 1”处的XMLHttpRequest “ http:// localhost:4200”已被CORS政策阻止:交叉来源 仅协议方案支持请求:http,data,chrome, chrome-extension,https。

更新,现在,在添加建议的代码更改后,错误已更改。现在如下:

从以下位置访问“ http:// localhost:60248 / api / page / 1”上的XMLHttpRequest 来源'http:// localhost:4200'已被CORS政策阻止: 对预检请求的响应未通过访问控制检查: 预检请求不允许重定向。

在Startup.cs中,我有这个:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: "AllowAll",
                builder =>
                {
                    builder.AllowAnyOrigin()
                        .WithMethods("PUT", "DELETE", "GET");
                });
        });

在我的控制器中,我有这个:

[Route("api/[controller]")]
[ApiController]
public class PageController : ControllerBase
{
    ...

    [EnableCors("AllowAll")]
    [HttpGet("{id:int}")]
    public async Task<IActionResult> GetPageData(int id)
    {
       ...

这是调用端点的Angular服务:

export class PageContentService {
  constructor(private http: HttpClient) { }

  getContent(id: number): Observable<PageContent> {

    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json');
    const httpOptions = {
      headers: headers
    }

    return this.http.get<PageContent>(`http://localhost:60248/api/page/${id}`, httpOptions);
  }
}

我认为可以解决这个问题,但显然不会。

我还需要做什么?

2 个答案:

答案 0 :(得分:2)

您还需要添加中间件。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
...

        app.UseCors();

...
    }

答案 1 :(得分:2)

我认为您还需要两件事:

  1. 就像vivek所说的那样,在您的Configure方法中,将.UseCors()添加到您的请求管道中。

  2. 在策略构建器的CORS-Config中添加.AllowAnyHeader(),我认为默认情况下不允许使用Content-Type-Header。