简体   繁体   中英

Enabling CORS in asp.net core

I created a simple api in .net core and trying to access that from react app, I get a CORS error. I enabled cors by following CORS with default policy and middleware section on

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

still I get cors error in my react app. not exactly sure where I am getting it wrong.

.net core api

namespace React_NalONE_API
{
    public class Startup
    {
        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
        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.AddCors(options =>
            {
                // options.AddPolicy(name: MyAllowSpecificOrigins,
                //                 builder =>
                //               {
                //                 builder.WithOrigins("http://localhost/*",
                //                                   "https://localhost/*");
                //         });

                options.AddDefaultPolicy(
                builder =>
                {
                    builder.WithOrigins("http://localhost/*",
                                        "https://localhost/*");
                });
            });
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers().RequireCors(MyAllowSpecificOrigins);
            });
        }
    }
}

React app

 componentDidMount () {
        console.log("The component is now mounted")
        this.setState({loading : true})
        fetch('https://localhost:44391/agency')
        .then(data => data.json())
        .then(data => this.setState({data, loading : false}))
      }

error

Access to fetch at 'https://localhost:44391/agency' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Your help is much appreciated Thanks R

From the document , you could know that:

Note: The specified URL must not contain a trailing slash (/). If the URL terminates with /, the comparison returns false and no header is returned.

For your requirement,it seems you want to allow CORS requests from all origins with any scheme ( http or https ),I suggest that you could use AllowAnyOrigin :

 services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    builder.AllowAnyOrigin();
                });
        });

Reference:

Another way is to change like below:

 services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    builder.WithOrigins("https://localhost:44391",
                                        "http://localhost:44391");
                });
        });

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