This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
/
RemoteAttribute.cs
320 lines (281 loc) · 12.6 KB
/
RemoteAttribute.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using Microsoft.AspNetCore.Mvc.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Mvc
{
/// <summary>
/// A <see cref="ValidationAttribute"/> which configures Unobtrusive validation to send an Ajax request to the
/// web site. The invoked action should return JSON indicating whether the value is valid.
/// </summary>
/// <remarks>Does no server-side validation of the final form submission.</remarks>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class RemoteAttribute : ValidationAttribute, IClientModelValidator
{
private string _additionalFields = string.Empty;
private string[] _additionalFieldsSplit = Array.Empty<string>();
private bool _checkedForLocalizer;
private IStringLocalizer _stringLocalizer;
/// <summary>
/// Initializes a new instance of the <see cref="RemoteAttribute"/> class.
/// </summary>
/// <remarks>
/// Intended for subclasses that support URL generation with no route, action, or controller names.
/// </remarks>
protected RemoteAttribute()
: base(errorMessageAccessor: () => Resources.RemoteAttribute_RemoteValidationFailed)
{
RouteData = new RouteValueDictionary();
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteAttribute"/> class.
/// </summary>
/// <param name="routeName">
/// The route name used when generating the URL where client should send a validation request.
/// </param>
/// <remarks>
/// Finds the <paramref name="routeName"/> in any area of the application.
/// </remarks>
public RemoteAttribute(string routeName)
: this()
{
RouteName = routeName;
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteAttribute"/> class.
/// </summary>
/// <param name="action">
/// The action name used when generating the URL where client should send a validation request.
/// </param>
/// <param name="controller">
/// The controller name used when generating the URL where client should send a validation request.
/// </param>
/// <remarks>
/// <para>
/// If either <paramref name="action"/> or <paramref name="controller"/> is <c>null</c>, uses the corresponding
/// ambient value.
/// </para>
/// <para>Finds the <paramref name="controller"/> in the current area.</para>
/// </remarks>
public RemoteAttribute(string action, string controller)
: this()
{
if (action != null)
{
RouteData["action"] = action;
}
if (controller != null)
{
RouteData["controller"] = controller;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteAttribute"/> class.
/// </summary>
/// <param name="action">
/// The action name used when generating the URL where client should send a validation request.
/// </param>
/// <param name="controller">
/// The controller name used when generating the URL where client should send a validation request.
/// </param>
/// <param name="areaName">The name of the area containing the <paramref name="controller"/>.</param>
/// <remarks>
/// <para>
/// If either <paramref name="action"/> or <paramref name="controller"/> is <c>null</c>, uses the corresponding
/// ambient value.
/// </para>
/// If <paramref name="areaName"/> is <c>null</c>, finds the <paramref name="controller"/> in the root area.
/// Use the <see cref="RemoteAttribute(string, string)"/> overload find the <paramref name="controller"/> in
/// the current area. Or explicitly pass the current area's name as the <paramref name="areaName"/> argument to
/// this overload.
/// </remarks>
public RemoteAttribute(string action, string controller, string areaName)
: this(action, controller)
{
RouteData["area"] = areaName;
}
/// <summary>
/// Gets or sets the HTTP method (<c>"Get"</c> or <c>"Post"</c>) client should use when sending a validation
/// request.
/// </summary>
public string HttpMethod { get; set; }
/// <summary>
/// Gets or sets the comma-separated names of fields the client should include in a validation request.
/// </summary>
public string AdditionalFields
{
get => _additionalFields;
set
{
_additionalFields = value ?? string.Empty;
_additionalFieldsSplit = SplitAndTrimPropertyNames(value)
.Select(field => FormatPropertyForClientValidation(field))
.ToArray();
}
}
/// <summary>
/// Gets the <see cref="RouteValueDictionary"/> used when generating the URL where client should send a
/// validation request.
/// </summary>
protected RouteValueDictionary RouteData { get; }
/// <summary>
/// Gets or sets the route name used when generating the URL where client should send a validation request.
/// </summary>
protected string RouteName { get; set; }
/// <summary>
/// Formats <paramref name="property"/> and <see cref="AdditionalFields"/> for use in generated HTML.
/// </summary>
/// <param name="property">
/// Name of the property associated with this <see cref="RemoteAttribute"/> instance.
/// </param>
/// <returns>Comma-separated names of fields the client should include in a validation request.</returns>
/// <remarks>
/// Excludes any whitespace from <see cref="AdditionalFields"/> in the return value.
/// Prefixes each field name in the return value with <c>"*."</c>.
/// </remarks>
public string FormatAdditionalFieldsForClientValidation(string property)
{
if (string.IsNullOrEmpty(property))
{
throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(property));
}
var delimitedAdditionalFields = string.Join(",", _additionalFieldsSplit);
if (!string.IsNullOrEmpty(delimitedAdditionalFields))
{
delimitedAdditionalFields = "," + delimitedAdditionalFields;
}
var formattedString = FormatPropertyForClientValidation(property) + delimitedAdditionalFields;
return formattedString;
}
/// <summary>
/// Formats <paramref name="property"/> for use in generated HTML.
/// </summary>
/// <param name="property">One field name the client should include in a validation request.</param>
/// <returns>Name of a field the client should include in a validation request.</returns>
/// <remarks>Returns <paramref name="property"/> with a <c>"*."</c> prefix.</remarks>
public static string FormatPropertyForClientValidation(string property)
{
if (string.IsNullOrEmpty(property))
{
throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(property));
}
return "*." + property;
}
/// <summary>
/// Returns the URL where the client should send a validation request.
/// </summary>
/// <param name="context">The <see cref="ClientModelValidationContext"/> used to generate the URL.</param>
/// <returns>The URL where the client should send a validation request.</returns>
protected virtual string GetUrl(ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var services = context.ActionContext.HttpContext.RequestServices;
var factory = services.GetRequiredService<IUrlHelperFactory>();
var urlHelper = factory.GetUrlHelper(context.ActionContext);
var url = urlHelper.RouteUrl(new UrlRouteContext()
{
RouteName = this.RouteName,
Values = RouteData,
});
if (url == null)
{
throw new InvalidOperationException(Resources.RemoteAttribute_NoUrlFound);
}
return url;
}
/// <inheritdoc />
public override string FormatErrorMessage(string name)
{
return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name);
}
/// <inheritdoc />
/// <remarks>
/// Always returns <c>true</c> since this <see cref="ValidationAttribute"/> does no validation itself.
/// Related validations occur only when the client sends a validation request.
/// </remarks>
public override bool IsValid(object value)
{
return true;
}
public virtual void AddValidation(ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
MergeAttribute(context.Attributes, "data-val", "true");
CheckForLocalizer(context);
var errorMessage = GetErrorMessage(context.ModelMetadata.GetDisplayName());
MergeAttribute(context.Attributes, "data-val-remote", errorMessage);
MergeAttribute(context.Attributes, "data-val-remote-url", GetUrl(context));
if (!string.IsNullOrEmpty(HttpMethod))
{
MergeAttribute(context.Attributes, "data-val-remote-type", HttpMethod);
}
var additionalFields = FormatAdditionalFieldsForClientValidation(context.ModelMetadata.PropertyName);
MergeAttribute(context.Attributes, "data-val-remote-additionalfields", additionalFields);
}
private static void MergeAttribute(IDictionary<string, string> attributes, string key, string value)
{
if (!attributes.ContainsKey(key))
{
attributes.Add(key, value);
}
}
private static IEnumerable<string> SplitAndTrimPropertyNames(string original)
{
if (string.IsNullOrEmpty(original))
{
return Array.Empty<string>();
}
var split = original
.Split(',')
.Select(piece => piece.Trim())
.Where(trimmed => !string.IsNullOrEmpty(trimmed));
return split;
}
private void CheckForLocalizer(ClientModelValidationContext context)
{
if (!_checkedForLocalizer)
{
_checkedForLocalizer = true;
var services = context.ActionContext.HttpContext.RequestServices;
var options = services.GetRequiredService<IOptions<MvcDataAnnotationsLocalizationOptions>>();
var factory = services.GetService<IStringLocalizerFactory>();
var provider = options.Value.DataAnnotationLocalizerProvider;
if (factory != null && provider != null)
{
_stringLocalizer = provider(
context.ModelMetadata.ContainerType ?? context.ModelMetadata.ModelType,
factory);
}
}
}
private string GetErrorMessage(string displayName)
{
if (_stringLocalizer != null &&
!string.IsNullOrEmpty(ErrorMessage) &&
string.IsNullOrEmpty(ErrorMessageResourceName) &&
ErrorMessageResourceType == null)
{
return _stringLocalizer[ErrorMessage, displayName];
}
return FormatErrorMessage(displayName);
}
}
}