【发布时间】:2020-07-09 16:11:04
【问题描述】:
我的Asp.Net Core 3.1 API返回422 Unprocessable Entity错误响应如下图:
{
"type": "https://test.com/modelvalidationproblem",
"title": "One or more model validation errors occurred.",
"status": 422,
"detail": "See the errors property for details.",
"instance": "/api/path",
"traceId": "8000003f-0001-ec00-b63f-84710c7967bb",
"errors": {
"FirstName": [
"The FirstName field is required."
]
}
}
如何反序列化此响应并将错误添加到Asp.Net Core 3.1 Razor Pages 中的模型验证错误?
我尝试创建如下所示的模型,
错误模型:
public class UnprocessableEntity
{
public string Type { get; set; }
public string Title { get; set; }
public int Status { get; set; }
public string Detail { get; set; }
public string Instance { get; set; }
public string TraceId { get; set; }
public Errors Errors { get; set; }
}
public class Errors
{
....// what should I need to add here? Keys and messages will be dynamic
}
但是我应该在Errors 类中添加什么?错误键和消息将是动态的。
一旦知道了以上内容,我就可以在我的 razor 页面中添加模型状态错误,如下所示,
using var responseStream = await response.Content.ReadAsStreamAsync();
var errorResponse = await JsonSerializer.DeserializeAsync<UnprocessableEntity>(responseStream);
foreach (var error in errorResponse.errors)
{
ModelState.AddModelError(error.key, error.Message[0]); // I'm stuck here
}
【问题讨论】:
标签: asp.net-core-webapi razor-pages asp.net-core-3.1 modelstate http-status-code-422