c# - 如何调试拒绝 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"));
解决方案
使用 StringContent 类的构造函数设置 Content-Type 标头。
推荐阅读
- docker - ENTRYPOINT、CMD 和运行优先级
- powerbi - Power BI 动态图例
- c# - 为什么当我向flowLayoutPanel中添加一定数量的控件时,添加的数量比c#中想要的多?
- excel - VB.Net:Excel 单元格周围的所有边框
- kubernetes - kube-proxy:另一个应用程序当前持有 xtables 锁
- linux - 如何将 localhost 重定向/映射到指向其他东西的东西?
- node.js - 如何将反应值传递给 Node.js api 调用
- php - 未在 Laravel 5.6 中加载引导 cdn
- python - 更改joined_at时区discord.py
- google-cloud-platform - gcloud cpu quota 本身是否需要任何费用?