繁体   English   中英

ASP.NET Core 网页忽略 Startup.cs 中的 CORS 策略

[英]ASP.NET Core webpage ignores CORS policy in Startup.cs

这不是之前问题的重复,因为他们的解决方案说要添加 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选项。 所以现在,它没有控制器,只有页面。


编辑:

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

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

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

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

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

}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM