【问题标题】:Angular 6 .net Web Api No 'Access-Control-Allow-Origin' header ErrorAngular 6 .net Web Api No 'Access-Control-Allow-Origin' header 错误
【发布时间】:2018-11-10 14:56:16
【问题描述】:

我正在使用带有 Angular 6、Vs Studio 的 Vs Code 开发 .net Core Web Api。 错误如下; - 加载资源失败:服务器响应状态为 500(内部服务器错误) - 请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost:4200' 因此不允许访问。响应是 HTTP 状态码 500。

// I added to Startup.cs;
ConfigureServices === >>> services.AddCors ();
Configure === >>>> app.UseCors (bldr => bldr.WithOrigins ("http: // 
localhost: 4200") .WithMethods ("GET", "POST"). AllowAnyHeader ());

问题在于;问题在 get 方法中得到解决,数据被检索但在 post 方法中不起作用。提前致谢。

【问题讨论】:

  • 您是否按照@Anton 在答案中的建议尝试了`app.UseCors(CorsOptions.AllowAll);`?
  • 我试过但没有

标签: angular asp.net-web-api asp.net-core .net-core asp.net-core-mvc


【解决方案1】:

请务必记住,services.AddCors() 必须位于 services.AddMvc() 之前,app.UseCors()app.UseMvc() 也是如此。

【讨论】:

    【解决方案2】:

    有多种方法可以解决这个问题,dotnet core documentation 讨论如何处理 CORS。

    这往往是仅在开发过程中出现的问题,因此这是我解决此问题的首选方法。

    将 CORS 规则添加到服务中,允许开发过程中的一切

    if (_env.IsDevelopment())
    {
        services.AddCors(options =>
        {
            options.AddPolicy("AllowAll",
                      p => p.AllowAnyOrigin()
                            .AllowAnyHeader()
                            .AllowAnyMethod()
                            .AllowCredentials());
        });
    }
    

    然后将创建的规则添加到 Application Builder:

    if (_env.IsDevelopment())
    {
        app.UseCors("AllowAll");
    }
    

    交替

    还有一个CORS browser extension可用于谷歌浏览器,我不确定其他浏览器。

    当我不想干预请求/响应标头时,这是我的首选,并且是当其他项目出现此问题时的快速解决方案,而不仅仅是 .net 核心。

    提醒一句,有时这个插件不起作用。

    【讨论】:

    • 我试过但没有。角;让 headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); options.responseType = ResponseContentType.Blob;让 body = JSON.stringify(sorguParametreri); return this.http.post(this.apiURL + "/AGranter/DownloadReport", body, options).map((response: any) => {
    猜你喜欢
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 2023-01-13
    • 2019-02-01
    • 1970-01-01
    相关资源
    最近更新 更多