【问题标题】:ASP.NET Core webpage ignores CORS policy in Startup.csASP.NET Core 网页忽略 Startup.cs 中的 CORS 策略
【发布时间】:2020-07-09 08:10:13
【问题描述】:

这不是之前问题的重复,因为他们的解决方案说要添加 CORS 策略。我的问题是关于为什么在这种情况下会忽略 CORS 政策,尽管它存在。


我正在运行一个基本的 ASP.NET Core 2.1 网页,它将与运行在 localhost:5082 的 docker 容器通信。 (是的,.NET Core 2.1 有点老了,但出于部门类型的原因,它目前对我们来说是必要的。)

自然,当尝试通过 Visual Studio 调试器运行该网页项目时,由于 CORS 策略,页面上的 AJAX 请求在尝试访问该容器时会失败。所以...我已经进入 Startup.cs 并添加了一个非常宽松的 CORS 政策,但由于某种原因,它被忽略了。

我尝试了几个类似的帖子和 SO 答案,它们都在做非常相似的事情,但这是我的 Startup.cs 可能看起来的示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace TheNamespace
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                    builder =>
                    {
                        builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials();
                    });
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // 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();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseCors("AllowAll");
            app.UseMvc();
        }
    }
}

注意对services.AddCorsapp.UseCors 的调用。不同的帖子和 SO 答案对此的表达方式略有不同,但都指向与此非常相似的Startup.cs

但这在某种程度上被忽略了,我对http://localhost:5082/... 的非常基本的 JavaScript GET 调用仍然失败,并显示此错误消息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5082/... (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

怎么了?


这是失败的 JavaScript(url 是一个字符串值):

var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', url, false);
//xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlHttp.send(null);
return xmlHttp.responseText;

编辑:

这不是一个 MVC 项目或任何花哨的东西。创建项目时,我只是选择了Web Application 的选项。所以现在,它没有控制器,只有页面。


编辑:

根据 cmets,这基本上是我的项目结构:

Pages:
    Shared:
        _CookieConsentPartial.cshtml
        _Layout.cshtml
        _ValidationScriptsPartial.cshtml
    _ViewImports.cshtml
    _ViewStart.cshtml
    Index.cshtml
Program.cs
Startup.cs

就网址而言,它是http://localhost:5082/api/buildcactus

【问题讨论】:

  • 尝试移动“app.UseCors("AllowAll");"在“app.UseStaticFiles();”之上打电话
  • 我知道您说您使用的是 2.1,但请仔细检查 - 在 2.2 中,有一个更改意味着允许 CORS 的所有内容不再有效:trailheadtechnology.com/…
  • 我认为如果您展示您的实际项目结构以及您正在调用的实际 URL,这将有所帮助。
  • 啊……当您的 JS 尝试访问您的端点时,您得到的 HTTP 状态代码是什么?
  • 扩展我之前的评论:在 ASP.NET Core 2.1 中,异常处理中间件会在请求管道未明确处理。这已在 2.2 中修复:github.com/dotnet/aspnetcore/issues/2378#issuecomment-405096602

标签: c# visual-studio asp.net-core cors asp.net-core-2.1


【解决方案1】:

这对我有用。构建器中的 CorsPolicyBuilder 配置策略。现在你可以在控制器中使用它了:

[EnableCors("AllowAll")]
public class MyController
{

}

app.UseCors("AllowAll") 单独可能不适用于 API 端点。尝试在控制器上显式添加[EnableCors("AllowAll")]

【讨论】:

    猜你喜欢
    • 2021-07-20
    • 2020-11-02
    • 2020-03-01
    • 2020-05-22
    • 2020-07-16
    • 2022-10-30
    • 2021-09-15
    • 2021-07-09
    • 2019-01-29
    相关资源
    最近更新 更多