c# - Asp.net Core Post 参数始终为 null

标签 c# .net asp.net-core asp.net-core-webapi

<分区>

我正在从 fiddler 发送 POST:

POST http://localhost:55924/api/Product HTTP/1.1
User-Agent: Fiddler
Host: localhost:55924
Content-Type: application/json; charset=utf-8
Content-Length: 84

{"Ean″:”1122u88991″,”Name″:”Post test″,"Description":"Post test desc"}

但是 Post 方法总是返回 null。

// POST api/Product
[HttpPost]
public IActionResult PostProduct([FromBody]Product product)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    _repo.Add(product);

    return CreatedAtRoute("GetToode",product);
}

当我使用 [FormBody] 时,产品始终为空,当不使用它时,产品有值但所有字段都为空。产品类别简单。

public class Product
{
    public int ProductID { get; set; }
    public string EAN { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int? CategoryID { get; set; }
}

我尝试按照 post 中的建议将 NullValueHandling 添加到 ConfigureServices但没有用。

services.AddMvc()
    .AddJsonOptions(jsonOptions =>
    {
        jsonOptions.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
    });

最佳答案

我只需要更正您的 POST 请求中的双引号就可以了。试试这个:

{"Ean":"1122u88991","Name":"Post test","Description":"Post test desc"}

请参阅下面的屏幕截图。

Screenshot

关于c# - Asp.net Core Post 参数始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39748153/

相关文章:

c# - asp.net core 上的静态文件

c# - UseInMemoryDatabase() 的 dotnet 核心没有重载方法需要 0 个参数

c# - SignalR - 仅适用于本地主机

c# - ManualResetEventSlim 上的 Wait()-ing 是否保证在取消时抛出?

java - java中有 “createObject”吗?

c# - 可以将 F# 类型的提供程序合并到 C# 中吗

c# - dotnet 核心方法 'ValidateOptions' ... 没有实现

c#:检查哪个项目正在调用类库

c# - 用双反斜杠替换反斜杠、正斜杠和双正斜杠

c# - 如何从不同的方法调用事件方法?