【问题标题】:Null binding from POST request body来自 POST 请求正文的空绑定
【发布时间】:2015-05-13 22:58:41
【问题描述】:

我在 ApiController 子类控制器中有 2 个 asp.net web api 操作。两种操作方法是 POST。一种方法是使用非空请求正文。但其他操作方法总是得到空请求正文。我不知道第二个 POST 操作不起作用的原因。请帮忙。

以下 POST 操作方法适用于非空请求正文绑定:方法签名中的参数“model”已正确绑定。

[HttpPost]
[Route("create/{sessionid:guid}")]
public HttpResponseMessage CreateAccount(Guid sessionid, UserAccountDto model)
{
    var result = new HttpResponseMessage(HttpStatusCode.OK);


    return Request.CreateResponse(HttpStatusCode.OK, model);
}

Dto class:

public class UserAccountDto
    {
        public long? AccountId { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string Salt { get; set; }
        public string PlainTextPassword { get; set; }
    }

Call with API by using Advanced Rest Client tool plugged in Chrome

POST http://localhost:55540/guests/create/13DD8111-8A00-48CE-997F-28EE3C88895D

{ 
    email:"meme@me.com",
    password:"fkdld",
    salt:"salt",
    plaintextpassword :"abc"
}

第二个 ApiController POST 操作方法不起作用。方法动作中的参数“model”始终为空;由于某种原因没有正确绑定。

[HttpPost]
    [Route("convert/{sessionid:guid}")]
    public IHttpActionResult ConvertAccount(Guid sessionid, LinkedAccountThinDto model)
    {
        var accountType = model.AccountType;
        var accountKey = model.AccountKey;

        return Ok();
    }

自定义 Dto 类:

public class LinkedAccountThinDto
{
    public string AccountType { get; set; }
    public string AccountKey { get; set; }
}

使用 Chrome 中的 Advanced Rest Client 工具调用 API

POST http://localhost:55540/guests/convert/13DD8111-8A00-48CE-997F-28EE3C88895D

{ 
        accounttype: “abcdf”,
        accountkey: “1234567”
} 

【问题讨论】:

  • 您是否尝试过针对 LinkedAccountThinDto 方法参数指定 [FromBody]?
  • 是的,我已经尝试过[FromBody],但是没有解决空绑定的问题。
  • 我不禁注意到您的第二个示例中的引号与第一个示例中的字符串引号不同。
  • 您是否尝试过更改大小写,例如AccountType 而不是 accounttype
  • 您能否在调试时检查Request 对象,看看两个请求是否来自相同?

标签: c# asp.net-web-api asp.net-web-api2


【解决方案1】:

正如 Stilgar 所说,我在使用 MS Word 而不是 Advanced Rest Client 工具的文本编辑器为第二个 Api 操作创建 JSON 字符串时犯了一个错误。这导致了工具无法理解的创建报价的问题。我直接在工具里面重新创建了JSON字符串,问题就解决了。

谢谢大家。

顺便说一句,以下 JSON 字符串在我的第二个 Api 方法中都可以正常工作,无论属性键和使用的引号的大小写如何:

{"AccountType": "abcdf","AccountKey": "1234567"} 
{"accounttype": "abcdf","accountkey": "1234567"} 
{accounttype: "abcdf",accountkey: "1234567"}

【讨论】:

    猜你喜欢
    • 2018-01-14
    • 2018-07-14
    • 2016-03-19
    • 2020-05-29
    • 2019-11-18
    • 2018-06-16
    • 2019-06-26
    • 2018-01-28
    • 1970-01-01
    相关资源
    最近更新 更多