Quick Configuration of Cross-Origin Resource Sharing (CORS) in ASP.NET Core

2019年12月12日 69点热度 0人点赞 0条评论
内容目录

In a Startup class, add a static variable:

        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

Configure global CORS in services:

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

Place the CORS middleware:

            app.UseHttpsRedirection();

            app.UseDefaultFiles(Program.Defaultfileoptions);
            app.UseStaticFiles();

            app.UseRouting();

#if CORS
            app.UseCors(MyAllowSpecificOrigins);
#endif

Once configured, specify which Controllers or Actions allow CORS.

To configure CORS globally, add the following in the middleware routing configuration:

.RequireCors(MyAllowSpecificOrigins)

Example:

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

                // Add SignalR service
                // endpoints.MapHub<MessageHubs>("/Message");
            });

If you only want to enable CORS for a specific Controller or Action, add the attribute above the Controller or Action:

    [EnableCors]

痴者工良

高级程序员劝退师

文章评论