首页 > 解决方案 > 如何调试拒绝 POST 请求的 ASP.NET Core WebAPI?

问题描述

我正在尝试向我制作的一个非常简单的测试 API 发送 POST 请求,但是它只是在请求到达控制器方法中的断点并返回 400 错误之前拒绝该请求。

Postman 发出的相同请求运行良好,而我用来调用 API 的相同代码在另一个 API 上运行良好。理想情况下,我想比较我的代码发出的请求和 Postman 发出的请求,但我不知道这是否可能。

这不是模型问题或路由问题。

控制器方法:

[HttpPost]
public void Post([FromBody] User user)
{
    user.CreatedAt = DateTime.Now;
    UserContainer.Users.Add(user);
}

调用 API 的代码:

HttpClientHandler handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };

HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri("https://localhost:5001/api/");

Task<HttpResponseMessage> task = client.PostAsync("user", new StringContent("{\"id\":\"7\",\"firstName\":\"Kanye\",\"lastName\":\"West\"}"));
task.Wait();
task.Result.IsSuccessStatusCode.Should().BeTrue();

模型:

public class User
{
    public int      Id        { get; set; }
    public DateTime CreatedAt { get; set; }
    public string   FirstName { get; set; }
    public string   LastName  { get; set; }
}

解决 了我需要替换这一行:

Task<HttpResponseMessage> task = client.PostAsync("user", new StringContent("{\"id\":\"7\",\"firstName\":\"Kanye\",\"lastName\":\"West\"}"));

有了这个:

Task<HttpResponseMessage> task = client.PostAsync("user", new StringContent("{\"id\":\"7\",\"firstName\":\"Kanye\",\"lastName\":\"West\"}", Encoding.UTF8, "application/json"));

标签: c#asp.net-web-apiasp.net-core.net-coreasp.net-core-webapi

解决方案


使用 StringContent 类的构造函数设置 Content-Type 标头。


推荐阅读