简体   繁体   中英

ASP.NET Core webpage ignores CORS policy in Startup.cs

This is not a duplicate of previous questions, because their solutions say to add a CORS policy. My question here is about why that CORS policy is being ignored in this case, despite its presence.


I'm getting a basic ASP.NET Core 2.1 webpage going, which will communicate with a docker container running at localhost:5082 . (Yes, .NET Core 2.1'sa little old, but it's a necessary evil for us at the moment, for departmental-type reasons.)

So naturally, when trying to run that webpage project through the Visual Studio debugger, the AJAX request on the page fails when trying to access that container, because of the CORS policy. So...I've gone in to Startup.cs and added a very liberal CORS policy, and for some reason, it's getting ignored.

I've tried several similar posts and SO answers, which are all doing very similar things, but this is an example of what my Startup.cs might look like:

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();
        }
    }
}

Note the calls to services.AddCors and app.UseCors . Different posts and SO answers have slightly different expressions of this, but they all point to having a Startup.cs that is very similar to this.

But this is getting ignored somehow, and my very basic JavaScript GET call to http://localhost:5082/... is still failing with this error message:

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).

What's wrong?


This is the JavaScript that's failing ( url is a string value):

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

EDIT:

This is not an MVC project or anything fancy at all. When creating the project, I just selected the option for Web Application . So right now, it doesn't have controllers, just pages.


EDIT:

Per the comments, this is basically my project structure:

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

In terms of the URL, it's http://localhost:5082/api/buildcactus .

This has worked for me. The CorsPolicyBuilder in builder configures the policy. Now you can use it in controllers:

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

}

app.UseCors("AllowAll") alone may not work for API endpoints. Try to add explicitly [EnableCors("AllowAll")] on the controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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