问题描述: 在ASP.Net Core 3.1的Web API中,接收POST请求的参数始终为NULL。
解决方法: 有几个可能的原因导致参数为NULL的问题。下面提供了几种可能的解决方法。
可以通过在请求的Header中添加Content-Type字段来设置正确的Content-Type。
例如,在使用HttpClient发送POST请求时,可以使用以下代码设置Content-Type:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
例如:
[HttpPost]
public IActionResult MyAction([FromBody] MyModel model)
{
//...
}
确保模型类的属性的getter和setter都是public。
例如:
public class MyModel
{
public string Property1 { get; set; }
public int Property2 { get; set; }
}
例如,如果请求的参数名称为Property1,那么模型类的属性名称也应为Property1。
例如:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.DictionaryKeyPolicy = null;
});
}
这将禁用Json序列化器的命名策略,确保属性名称的大小写与请求的参数名称匹配。
这些解决方法中的一种或多种可能会解决参数为NULL的问题。根据具体情况选择适合的解决方法。
上一篇:ASP.NET Core 3.1 - 添加子项到Razor局部视图
下一篇:ASP.NET Core 3.1 - WebApplicationFactory - WebApplicationFactoryContentRootAttribute的正确用法是什么?