fin*_*s10 5 modelstate http-status-code-422 asp.net-core-webapi razor-pages asp.net-core-3.1
我的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."
]
}
}
Run Code Online (Sandbox Code Playgroud)
如何反序列化此响应并将错误添加到模型验证错误中Asp.Net Core 3.1 Razor Pages?
我尝试创建如下所示的模型,
错误模型:
{
"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."
]
}
}
Run Code Online (Sandbox Code Playgroud)
但是我应该在Errors课堂上添加什么?错误键和消息将是动态的。
一旦了解了上述情况,我就可以在我的 razor 页面中添加模型状态错误,如下所示,
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
}
Run Code Online (Sandbox Code Playgroud)
首先,您应该确保关键字段名称与 api( ) 返回的 json 相同pay attention to case。
public class UnprocessableEntity
{
public string type { get; set; }
public string tTitle { 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; }
}
Run Code Online (Sandbox Code Playgroud)
然后,类的字段Errors应该包含已验证类的所有字段,并且字段名称应该一致,但是需要define their type as an array to receive,因为json中错误返回的每个字段都是一个数组。(这里我创建了一个简单的验证类,名为StudInfo):
public class StudInfo
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
public class Errors
{
public List<string> Id { get; set; }
public List<string> Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后您可以使用如下代码:
using var responseStream = await response.Content.ReadAsStreamAsync();
var errorResponse = await JsonSerializer.DeserializeAsync<UnprocessableEntity>(responseStream);
var t = typeof(Errors);
var fieldNames = typeof(Errors).GetProperties()
.Select(field => field.Name)
.ToList();
foreach (var name in fieldNames)
{
List<string> errorLists = (List<string>)errorResponse.errors.GetType().GetProperty(name).GetValue(errorResponse.errors);
if (errorLists != null)
{
ModelState.AddModelError(name, errorLists[0]);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6112 次 |
| 最近记录: |