// 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.Linq; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace Microsoft.AspNetCore.Mvc { /// /// This attribute can be used on action parameters and types, to indicate model level metadata. /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public class BindAttribute : Attribute, IModelNameProvider, IPropertyFilterProvider { private static readonly Func _default = (m) => true; private Func _propertyFilter; /// /// Creates a new instance of . /// /// Names of parameters to include in binding. public BindAttribute(params string[] include) { var items = new List(); foreach (var item in include) { items.AddRange(SplitString(item)); } Include = items.ToArray(); } /// /// Gets the names of properties to include in model binding. /// public string[] Include { get; } /// /// Allows a user to specify a particular prefix to match during model binding. /// // This property is exposed for back compat reasons. public string Prefix { get; set; } /// /// Represents the model name used during model binding. /// string IModelNameProvider.Name => Prefix; /// public Func PropertyFilter { get { if (Include != null && Include.Length > 0) { if (_propertyFilter == null) { _propertyFilter = (m) => Include.Contains(m.PropertyName, StringComparer.Ordinal); } return _propertyFilter; } else { return _default; } } } private static IEnumerable SplitString(string original) { if (string.IsNullOrEmpty(original)) { return Array.Empty(); } var split = original.Split(',').Select(piece => piece.Trim()).Where(piece => !string.IsNullOrEmpty(piece)); return split; } } }