我的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
课堂上添加什么?错误键和消息将是动态的。
一旦知道了上述内容,我就可以在我的剃须刀页面中添加模型状态错误,如下所示,
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
}