【问题标题】:Access to XMLHttpRequest has been blocked by CORS policy in ASP.NET COREASP.NET CORE 中的 CORS 策略已阻止访问 XMLHttpRequest
【发布时间】:2020-03-01 05:04:39
【问题描述】:

我尝试使用 ajax 从我的客户端连接到 API 服务器,但在响应中出现错误: 从源“http://localhost:5003”访问 XMLHttpRequest 在“https://localhost:44381/api/webinars”已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问控制允许源” ' 请求的资源上存在标头。 我试图在 API 中编辑 CROS 策略,但我仍然有同样的错误。 这是我来自 MVC 的 ajax 代码:

 $.ajax({
            url: "https://localhost:44381/api/webinars",
            type: 'POST',
            headers: {
                contentType: "application/json",
            },
            body: JSON.stringify(body),
            success: function (data) {
                console.log(data);
            },
            failure: function (err) {
                console.log(err);
            }

        });

从 API 启动:

  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("AllowMyOrigin",
            builder => builder.WithOrigins(
                "http://localhost:5003/",
                "http://apirequest.io")
                .WithMethods("POST","GET","PUT")
                .WithHeaders("*")
                );
        });
          //code
    }

   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //code
        app.UseCors("AllowMyOrigin");
        app.UseHttpsRedirection();
        app.UseMvc();
    }
}

API 中的控制器:

[EnableCors("AllowMyOrigin")]

[Route("api/[controller]")]
[ApiController]
public class WebinarsController : ControllerBase
{
        // POST: api/Webinars
    [HttpPost]
    public async Task <ActionResult> PostAsync([FromBody] Item newItem)
    {     
         //code
      }
 }

感谢您的回答。

【问题讨论】:

标签: c# ajax api model-view-controller cross-domain-policy


【解决方案1】:

你应该替换 app.UseMvc(); 与

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

【讨论】:

  • 也不需要使用已经在启动时配置的[EnableCors("AllowMyOrigin")]
  • 您的评论可能会更好地编辑您的答案。谢谢!
猜你喜欢
  • 2019-12-18
  • 2020-05-05
  • 2021-03-27
  • 2021-10-11
  • 2019-09-23
  • 2019-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多