【问题标题】:Model Binding returns null model模型绑定返回空模型
【发布时间】:2018-03-15 04:41:12
【问题描述】:

我无法解决动作中的模型绑定问题。

它确实绑定,但不是所有时间。有时,该值为 null,因此它当然会引发错误。

这似乎发生在大约 50% 的时间里,有时是在用户登录 4 分钟或更长时间之后。

这是动作:

[HttpPost]
public IActionResult Post([FromBody]Csr csr)
{
    try
    {
        if(csr == null)
        {
            throw new Exception("Associate Controller recieved csr parameter when posting a new CSR");
        }
        //csr.ParentCsrId = this.GetCurrentCsr().CsrId;
        csr.InsertedDate = DateTime.Now;
        csr.UpdatedDate = DateTime.Now;
        return Ok(_associateRepository.Add(csr));
    }
    catch (Exception ex)
    {
        LogException(ex, "Associate Controller", "Post([FromBody]Csr csr)");
        throw ex;
    }
}

异常被抛出并正确记录。

这是根据浏览器发布的数据:

标题:

POST /api/associate HTTP/1.1
Host: portal.5-15globalenergy.it
Connection: keep-alive
Content-Length: 557
Accept: application/json
Origin: https://portal.5-15globalenergy.it
Authorization: Bearer xxxzy    User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36
Content-Type: application/json
Referer: https://portal.5-15globalenergy.it/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

主体:

{"csrTypeId":1,"countryId":2,"stateCode":"SO","birthCountryId":2,"birthStateCode":"SO","city":"Sondrio","streetPart":"STAZIONE","birthCity":"Sondrio","firstName":"Test","lastName":"User","maritalStatusId":2,"citizenshipCountryId":2,"personalTaxNum":"xxxxxx","streetName":"VIA SAN GOTTARDO","streetNum":"11","zip":"53216","landPhone":"231562145","mobilePhone":"231562145","email":"test@GMAIL.IT","bankAccountKey":"123625478325621","birthDate":"18/04/1969","orderStatusId":3,"streetCode":"","parentCsrId":"2130","syncStatusId":1,"languageId":3}

如果绑定有错误,有没有办法捕获它?

【问题讨论】:

  • 你能在你的开发工作站上重现吗?
  • 它总是对我有用。
  • 一个注释——你发布了一个不记名令牌。除非您欢迎任何人使用您的 Web API,否则最好不要这样做。

标签: asp.net-core asp.net-core-2.0


【解决方案1】:

我终于解决了这个问题。这里是要点:如果你得到一个空模型,但数据是在 Web 请求中传递的,这意味着模型绑定失败。

就我而言,格式错误的日期字符串无法转换为日期。结果是整个模型为空,而不仅仅是数据字段。

获取错误的方法是通过 ModelState 对象。就我而言,没有返回错误消息。但是返回了一个异常对象。

以下是将其连接成字符串的代码:

                string desc = "";
                foreach (var modelState in ViewData.ModelState.Values)
                {

                    foreach (var error in modelState.Errors)
                    {
                        if(!String.IsNullOrWhiteSpace(error.ErrorMessage))
                            desc = desc + " " + error.ErrorMessage.ToString();

                        if(error.Exception != null)
                        {
                            desc = desc + " Exception: " + error.Exception.ToString();
                        }

                    }
                }

【讨论】:

  • 你是对的,事实上,任何使用模型绑定的方法总是以if (!ModelState.IsValid) return View(); 或更专业的处理开头是最佳实践。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-22
  • 1970-01-01
  • 1970-01-01
  • 2014-05-29
  • 2019-04-03
  • 2013-08-11
相关资源
最近更新 更多