【问题标题】:.NET WebAPI not parsing [FromBody] properly from request content.NET WebAPI 无法从请求内容中正确解析 [FromBody]
【发布时间】:2018-01-29 09:10:31
【问题描述】:

我习惯了 HTTP 内容协商的流程,但以下内容似乎有些不合适:

我有一个具有以下内容的 .NET WebApi 控制器:

    /// <summary>
    /// Search for Records corresponding to the given criterias
    /// </summary>
    [AcceptVerbs("POST")]
    public async Task<IHttpActionResult> SearchRecord([FromBody]SearchPeopleModel recordSearchModel)
    {
        var recordService = Context.Services.Get<IRecordService>();
        var result = await recordService.SearchRecord(recordSearchModel);
        return Jsonify(result);
    }

使用Fiddler,请求内容如下:

POST http://localhost:43465/api/Record/SearchRecord HTTP/1.1
Host: localhost:43465
Connection: keep-alive
Content-Length: 72
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json
Origin: (hidden)
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 
(KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36
Content-Type: application/json
Referer: http://localhost:43465/
Accept-Encoding: gzip, deflate, br
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: ASP.NET_SessionId=(hidden)

{"Any":"mat","Firstname":"","Lastname":"","Birthname":"","PatientId":""}

调试 WebApi 时生成的 recordSearchModel 为 NULL。 我已经尝试过使用正文内容和 JSON.stringify/not,这似乎也不是问题。

我一定是错过了什么,但是……我看不到在哪里!希望有人能帮忙!

EDIT:作为这里的请求 searchPeopleModel 类。 RecordService 的实现与这里的问题无关,我就不展示了。

public class SearchPeopleModel
{
    public string Any {get; set;}
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Birthname { get; set; }
    public DateTime? BirthDate { get; set; }
    public Guid? PatientId { get; set; }
}

我可能不清楚一些精度:当 ASP.NET WEB API 接收到请求时,recordSearchModel 为空,其余代码按预期完美运行。

【问题讨论】:

  • 能否提供RecordService代码。
  • 与不同的模型类相同,代码对我有用。
  • 你能展示 SearchPeopleModel 类吗?
  • 根据要求,EDIT 添加了 searchPeopleModel 类实现
  • 它仍然为我工作

标签: json post asp.net-web-api


【解决方案1】:

我终于把这个挖出来了。

出现参数

public Guid? PatientId { get; set; }

默认情况下,asp.net webapi 无法对来自 SearchPeopleModel 的反序列化。 为了使这种行为起作用,我们必须发送:

{"Any":"mat","Firstname":"","Lastname":"","Birthname":""}

代替:

{"Any":"mat","Firstname":"","Lastname":"","Birthname":"","PatientId":""}

原因: "" 不能变成有效的空 Guid。 “[some-valid-guid]”虽然有效。

希望它可以帮助某人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-09
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2014-06-10
    • 2017-08-27
    • 2023-02-03
    相关资源
    最近更新 更多