模型绑定返回null模型

时间:2018-03-14 16:00:09

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

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

它会绑定,但不是所有的时间。有时,该值为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}

如果绑定中有错误,有没有办法陷阱?

1 个答案:

答案 0 :(得分:3)

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

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

获取错误的方法是通过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();
                        }

                    }
                }