【问题标题】:Why does sending POST request to asp.net core fail?为什么向 asp.net core 发送 POST 请求失败?
【发布时间】:2019-07-10 15:39:24
【问题描述】:

我有一个 ASP.net 核心 API 项目,我试图在 Firefox 中向它发送 POST 请求,但我总是收到一条错误消息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:44302/api/posts. (Reason: CORS request did not succeed).

如果我查看发送的请求,我可以看到它是一个返回 204 No Content 的 OPTIONS 请求。 POST请求根本没有发送,我可以通过检查内容没有改变来验证。

Chrome 是另一回事。当我发送相同的请求时,我会收到不同的错误消息:

POST https://localhost:44302/api/posts net::ERR_INVALID_HTTP_RESPONSE

这次我可以看到 2 个请求发送:

看起来像这样:

还有这个:

最后,如果我在 Postman 中尝试,它完全可以正常工作。

这是我用来发送请求的代码:

async createPost () {
  const timestamp = new Date()
  const data = {
    title: 'Some test post',
    body: 'Some test content',
    timePosted: timestamp,
    timePublished: timestamp,
    timeUpdated: timestamp,
    isVisible: true
  }
  const response = await axios.post('https://localhost:44302/api/posts', data)
  // do something with the response
},

这是该路由的控制器操作设置:

[HttpPost("api/posts/")]
public ActionResult Create([FromBody] BlogPost blogPost)
{
    _blogPostService.Create(blogPost);
    return CreatedAtAction("Create", blogPost);
}

这是我用于 BlogPost 的模型:

public class BlogPost
{
    public int Id { get; set; }

    public string Title { get; set; }

    public string Body { get; set; }

    public DateTime TimePosted { get; set; }

    public DateTime TimePublished { get; set; }

    public DateTime TimeUpdated { get; set; }

    public bool IsVisible { get; set; }
}

这就是我设置 CORS 的方式:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options => {
        options.AddPolicy("AllowAll", policy => {
            policy.WithOrigins("http://localhost:8080")
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();
        });
    });
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseCors("AllowAll");
    app.UseMvc();
}

知道为什么会这样吗?

【问题讨论】:

  • 您是否尝试过使用AllowAnyOrigin 而不是WithOrigins 来检查它是否有效?
  • 我刚刚试了一下,得到了同样的结果。
  • 尝试从策略设置代码中取出AllowCredentials()
  • 还是没有运气。如果它有帮助,我尝试了更多的东西,我发现如果我发送没有正文的发布请求,我没有这个问题。
  • 我什至尝试让 Visual Studio 为控制器搭建脚手架,并尝试在控制器和操作上使用 EnableCors 属性。还是什么都没有。

标签: asp.net cors axios


【解决方案1】:

原来这是 dotnet core sdk 的问题(在版本 2.2.101 上)。见this。解决方案是更新到最新版本,现在一切正常。

【讨论】:

    猜你喜欢
    • 2020-04-06
    • 1970-01-01
    • 2021-02-01
    • 2016-05-12
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    相关资源
    最近更新 更多