c# - ASP.NET CORE 中的 CORS 策略阻止了对 XMLHttpRequest 的访问

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

我尝试使用 ajax 从我的侧客户端连接到 API 服务器,但我在响应中收到错误:
访问 XMLHttpRequest ' https://localhost:44381/api/webinars '来自原点' http://localhost:5003 ' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin” header 。
我尝试在 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 中的 Controller :
[EnableCors("AllowMyOrigin")]

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

谢谢你的回答。

最佳答案

你应该替换 app.UseMvc();

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

关于c# - ASP.NET CORE 中的 CORS 策略阻止了对 XMLHttpRequest 的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58700916/

相关文章:

javascript - 如何使用ajax post请求从输入中放入参数?

java - Java 中是否有用于文本分析/挖掘的 API?

python-3.x - 在 google-vision text-detection api 中在哪里使用语言提示?

c# - 使用 Linq 从不包括特定成员列表的集合中选择项目的优化方法

c# - Minimod Pretty Print - 如何自定义换行符?

javascript - ASP .NET On_Load 方法未执行

javascript - MVC Ajax Javascript OnComplete 参数函数 'undefined'

c# - 使用 selenium C# 查找和替换文本文件中的数据

ajax 调用后的 Javascript 目标

reactjs - 如何有一个单独的 js 文件来处理 Reactjs 中的 API 调用