繁体   English   中英

.net 内核 2.1 CORS api

[英].net core 2.1 CORS api

我有一个 api 可以处理 ajax 后的请求。 当我调用它时,我收到了臭名昭著的 Cors 错误消息:

CORS 策略已阻止从源 '' 在 '' 访问 XMLHttpRequest:请求的资源上不存在“Access-Control-Allow-Origin” header

没问题。 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. 问题是我似乎无法让它工作。

这是我的 Sarup.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

}

}

这是我的 controller 的路线属性:

    [Route("api/v23")]

这是我的方法签名

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

最后是我的 ajax 请求:

$.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);
                }
            });

我尝试将 [Enable CORS("__myAllowSpecificOrigins") 属性添加到 controller,但这也不起作用。 这应该不难,我显然遗漏了一些明显的东西。
有什么建议吗?

尝试将 AddCors 的语法更改为:

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

暂无
暂无

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

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