/
ValidationProblemDetails.cs
92 lines (81 loc) · 3.4 KB
/
ValidationProblemDetails.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Core;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Microsoft.AspNetCore.Mvc
{
/// <summary>
/// A <see cref="ProblemDetails"/> for validation errors.
/// </summary>
[JsonConverter(typeof(ValidationProblemDetailsJsonConverter))]
public class ValidationProblemDetails : HttpValidationProblemDetails
{
/// <summary>
/// Initializes a new instance of <see cref="ValidationProblemDetails"/>.
/// </summary>
public ValidationProblemDetails()
{
Title = Resources.ValidationProblemDescription_Title;
}
/// <summary>
/// Initializes a new instance of <see cref="ValidationProblemDetails"/> using the specified <paramref name="modelState"/>.
/// </summary>
/// <param name="modelState"><see cref="ModelStateDictionary"/> containing the validation errors.</param>
public ValidationProblemDetails(ModelStateDictionary modelState)
: base(CreateErrorDictionary(modelState))
{
}
private static IDictionary<string, string[]> CreateErrorDictionary(ModelStateDictionary modelState)
{
if (modelState == null)
{
throw new ArgumentNullException(nameof(modelState));
}
var errorDictionary = new Dictionary<string, string[]>(StringComparer.Ordinal);
foreach (var keyModelStatePair in modelState)
{
var key = keyModelStatePair.Key;
var errors = keyModelStatePair.Value.Errors;
if (errors != null && errors.Count > 0)
{
if (errors.Count == 1)
{
var errorMessage = GetErrorMessage(errors[0]);
errorDictionary.Add(key, new[] { errorMessage });
}
else
{
var errorMessages = new string[errors.Count];
for (var i = 0; i < errors.Count; i++)
{
errorMessages[i] = GetErrorMessage(errors[i]);
}
errorDictionary.Add(key, errorMessages);
}
}
}
return errorDictionary;
static string GetErrorMessage(ModelError error)
{
return string.IsNullOrEmpty(error.ErrorMessage) ?
Resources.SerializableError_DefaultError :
error.ErrorMessage;
}
}
/// <summary>
/// Initializes a new instance of <see cref="ValidationProblemDetails"/> using the specified <paramref name="errors"/>.
/// </summary>
/// <param name="errors">The validation errors.</param>
public ValidationProblemDetails(IDictionary<string, string[]> errors)
: base(errors)
{
}
/// <summary>
/// Gets the validation errors associated with this instance of <see cref="HttpValidationProblemDetails"/>.
/// </summary>
public new IDictionary<string, string[]> Errors => base.Errors;
}
}