我有模型:
public class PushManyRequest
{
[JsonProperty("ids")]
public List<string> Ids { get; set; }
}
对于我的控制器,我有以下签名:
public async Task<IActionResult> PushMany([FromBody] PushManyRequest request)
{
...
}
如您所见,我正在尝试将请求映射到模型。而且方便易懂! 我可以添加[Required(ErrorMessage=<message>)]
属性,如果没有ids
,我将对客户端有自己的错误
但是,如果客户端向我传递了无效的 JSON,该怎么办?例如:
{
"ids": [
"123",
"234"
"235 <---------------------- invalid!!!
]
}
我会为客户回答如下:
{
"status": "error",
"description": [
"Unterminated string. Expected delimiter: ". Path 'ids[991]', line 999, position 1.",
"Unexpected end when deserializing array. Path 'ids[991]', line 999, position 1.",
"Unexpected end when deserializing object. Path 'ids[991]', line 999, position 1."
]
}
如您所见,它非常不友好。这是我的内部解析错误,客户不需要知道它。我想返回类似以下内容:
{
"status": "error",
"description": "Sorry, but your JSON is invalid. Please, check it and try again"
}
但是我不明白我可以在哪里写它以及如何捕捉这种情况。有什么想法吗?谢谢!
你应该研究一下模型状态。
if (!ModelState.IsValid)
{
IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);
foreach (ModelError item in allErrors)
{
orderErrors += item.ErrorMessage;
break;
}
using (var stream = new MemoryStream())
{
var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
context.Request.InputStream.Seek(0, SeekOrigin.Begin);
context.Request.InputStream.CopyTo(stream);
string requestBody = Encoding.UTF8.GetString(stream.ToArray());
log.write_to_log(requestBody, "null", "ModelState is not valid - " + orderErrors); //Saves to your log
return new HttpResponseMessage((HttpStatusCode)400);
}
}
if (orderErrors != "")
{
return new HttpResponseMessage((HttpStatusCode)400);
}
else
{
//Something happens
}
这样的事情应该^^