【问题标题】:.NET Core API with CORS from javascript [closed]带有来自javascript的CORS的.NET Core API [关闭]
【发布时间】:2019-03-15 17:24:36
【问题描述】:

我的 API 托管在与将访问它的 Web 应用程序不同的 URL 上。我目前已将 CORS 配置为允许我的 API 启动中的所有内容:

配置服务:

        services.AddCors(options => {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

配置:

app.UseCors("CorsPolicy");
app.UseMvc();

如果我在浏览器中键入 API URL,它会正常返回请求并按预期取回我的数据。

但是当我尝试使用 javascript 进行 API 调用时:

var xhr = new XMLHttpRequest();    
xhr.open('GET', 'https://api.example.com/Controller');
xhr.onload = function () {
    if (xhr.status === 200) {
        alert('Response is ' + xhr.responseText);
        console.log('Response is ' + xhr.responseText);
    }
    else {
        alert('Request failed.  Returned status of ' + xhr.status);
        console.log('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send();

它失败了,我在控制台中收到以下错误消息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the 
remote resource at https://api.example.com/Controller. (Reason: CORS header 
‘Access-Control-Allow-Origin’ missing).[Learn More]

我在这里遗漏了什么,需要进行哪些调整才能使其正常工作?

【问题讨论】:

标签: javascript .net reactjs asp.net-core-webapi


【解决方案1】:

这原来是我的 API 中的一个错误,我调用的方法抛出了 500。我仍然不明白为什么 Firefox 控制台将此报告为 CORS 问题,但似乎确实如此。一旦我修复了错误,消息就消失了

【讨论】:

  • 默认情况下,服务器通常不会将 Access-Control-Allow-Origin 响应标头或其他自定义标头添加到 5xx 响应中。在服务器开始执行您的应用程序代码之前,可能会发生 5xx 错误。因此,在客户端,浏览器会看到来自服务器的 (500) 响应,该响应缺少 Access-Control-Allow-Origin 响应标头。因此,浏览器在控制台中记录一条消息,就像它在其他任何时候某些前端 JavaScript 代码尝试从缺少 Access-Control-Allow-Origin 标头的响应中读取标头一样。
【解决方案2】:
  1. 在 ConfigureServices 方法中在 Service.AddCors() 之后启动 MVC
  2. 在配置方法中调用 app.UseMVC() 在 app.UseCors() 之后

顺序在这里非常重要。这是完整的 Start.cs 应该如下所示:--

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                //.AllowCredentials()
                )
                ;
        });

        services.AddMvc();
       // EnableCorsAttribute

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors("CorsPolicy");
        app.UseMvc();
        //app.UseCors("CorsPolicy");

    }

希望对你有帮助

【讨论】:

  • 这正是我所拥有的,我更新了我的问题以将代码包含在 Configure() 中。正如我所说的,问题不在于它失败了,如果你把 url 放在一个浏览器中它工作正常,那就是来自 JS 的调用会产生这个错误
猜你喜欢
  • 2021-07-31
  • 2021-03-13
  • 1970-01-01
  • 1970-01-01
  • 2017-06-09
  • 2018-12-15
  • 2011-08-05
  • 1970-01-01
  • 2018-09-18
相关资源
最近更新 更多