This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
/
DataMemberRequiredBindingMetadataProvider.cs
56 lines (50 loc) · 1.98 KB
/
DataMemberRequiredBindingMetadataProvider.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
// 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.Linq;
using System.Reflection;
using System.Runtime.Serialization;
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Metadata
{
/// <summary>
/// An <see cref="IBindingMetadataProvider"/> for <see cref="DataMemberAttribute.IsRequired"/>.
/// </summary>
public class DataMemberRequiredBindingMetadataProvider : IBindingMetadataProvider
{
/// <inheritdoc />
public void CreateBindingMetadata(BindingMetadataProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
// Types cannot be required; only properties can
if (context.Key.MetadataKind != ModelMetadataKind.Property)
{
return;
}
if (context.BindingMetadata.IsBindingRequired)
{
// This value is already required, no need to look at attributes.
return;
}
var dataMemberAttribute = context
.PropertyAttributes
.OfType<DataMemberAttribute>()
.FirstOrDefault();
if (dataMemberAttribute == null || !dataMemberAttribute.IsRequired)
{
return;
}
// isDataContract == true iff the container type has at least one DataContractAttribute
var containerType = context.Key.ContainerType.GetTypeInfo();
var isDataContract = containerType.IsDefined(typeof(DataContractAttribute));
if (isDataContract)
{
// We don't need to add a validator, just to set IsRequired = true. The validation
// system will do the right thing.
context.BindingMetadata.IsBindingRequired = true;
}
}
}
}