简体   繁体   中英

.net core 2.1 CORS api

I've got an api that handles a post ajax request. When I call it, I'm getting the infamous Cors error message:

Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

No problem. I've done this before and their is plenty of resources out there (eg Enable CORS in ASP .NET Core 2.1 Web Api ) describing how to add a cors policy to the startup. Problem is I can't seem to get it to work.

Here is my Sartup.cs:

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

    readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";


    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(MyAllowSpecificOrigins,
            builder =>
            {
                builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
            });
        });

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        {
            // User settings
            options.User.RequireUniqueEmail = true;
            options.SignIn.RequireConfirmedEmail = true;

            // Password settings
            options.Password.RequireDigit = true;
            options.Password.RequiredLength = 8;
            options.Password.RequiredUniqueChars = 1;
            options.Password.RequireLowercase = false;
            options.Password.RequireNonAlphanumeric = true;
            options.Password.RequireUppercase = false;
        })

            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // Add application services.
        services.AddTransient<IEmailSender, EmailSender>();
        services.AddAntiforgery(o => o.SuppressXFrameOptionsHeader = true);

        services.AddMvc(options =>
        {
            options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());

        });

    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
        RoleManager<IdentityRole> roleManager, IServiceProvider serviceProvider)
    {

        app.UseCors(MyAllowSpecificOrigins);

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
            app.UseDatabaseErrorPage();
            app.UseCors(MyAllowSpecificOrigins);
        }
        else
        {

            app.UseExceptionHandler("/Home/Error");
            app.UseCors(MyAllowSpecificOrigins);

        }

        app.UseStaticFiles();
        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        //UserDbContextSeed.Seed(serviceProvider).Wait();
    }//Configure

}

}

Here is my route attribute for my controller:

    [Route("api/v23")]

Here's my method signature

  [Route("[action]")]
    [HttpPost]       
    [IgnoreAntiforgeryToken]
    public IActionResult Post_Data(model v){......}

Finally here is my ajax requtest:

$.ajax({
                type: 'POST',
                url: 'Myserver/api/v23/Post_Data',
                dataType: 'json',
                contentType: "application/json", //
                data: JSON.stringify(Param),
                success: function (result) {
                     console.log(results);
                },
                error: function (request, status, error) {
                    console.log(error);
                }
            });

I've tried adding the [Enable CORS("__myAllowSpecificOrigins") attribute to the controller, but that doesn't work either. This shouldn't be hard, I'm obviously missing something obvious.
Any suggestion?

Try to change syntax of AddCors to this:

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

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