CORS无法用于从Ajax到ASP.NET Core Web API的调用 [英] CORS not working for calls from Ajax to ASP.NET Core Web API

查看:62
本文介绍了CORS无法用于从Ajax到ASP.NET Core Web API的调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它将在Ajax调用上引发此错误.我还使用命名策略在Startup.cs中尝试了这些行.我在网上找到的所有方法均无效.我确定我在某个地方犯了一些愚蠢的错误,但我没有看到它.

It throws this error on the Ajax call. I also tried these lines in Startup.cs with named policy. None of the ways that I found online, works. I'm sure I'm making some silly mistake somewhere, I'm not seeing it.

builder.WithOrigins("https://localhost:44380")
builder.WithOrigins("localhost:44380")
builder.WithOrigins("localhost")
[EnableCors("MyPolicy")] //in Controller.cs

Chrome浏览器控制台出现错误:

Error from Chrome Browser Console:

Controller.cs

Controller.cs

[Route("api/itexit")]
[EnableCors]
[ApiController]
public class ITExitController : ControllerBase
{
    //code...
}

Startup.cs

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddSwaggerGen();

    services.AddCors();

    string connectionString = Configuration.GetConnectionString("DefaultConnection");
    services.AddDbContext<CoCFormsContext>(options => options.UseSqlServer(connectionString));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "CoCForms.API");
    });

    app.UseHttpsRedirection();

    app.UseRouting();
    app.UseCors(builder =>
    {
        builder
        .AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader();
    });
    app.UseAuthorization();

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

.cshtml页面中的Ajax调用

Ajax call from .cshtml page

$.ajax({
    url: url,
    type: "GET",
    crossDomain: true,
    dataType: 'json',
    //dataType: 'jsonp',
    success: function (data,textstatus,jqXHR) {
//process data
    },
    error: function (jqXHR, textstatus, exception) {
//process exception
    }
});

推荐答案

尝试使用这样的命名策略:

Try to use the named policy like this:

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

还有这个

 app.UseCors("MyPolicy");

在这种情况下,您不需要控制器中的[EnableCors].仅在使用AddDefaultPolicy时才需要它....

And you don't need [EnableCors] in the controller in this case. You need it only if you use AddDefaultPolicy....

这篇关于CORS无法用于从Ajax到ASP.NET Core Web API的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆