为什么向asp.net core发送POST请求失败?

时间:2019-02-16 20:11:18

标签: asp.net cors axios

我有一个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请求,我可以通过检查内容没有更改来验证。

enter image description here

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

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

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

enter image description here

看起来像这样:

enter image description here

这:

enter image description here

最后,如果我在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();
}

关于为什么发生这种情况的任何想法吗?

1 个答案:

答案 0 :(得分:0)

原来是dotnet核心sdk(版本2.2.101)存在问题。参见this。解决方案是将其更新到最新版本,现在一切正常。