繁体   English   中英

如何将 DataMember Name 用于 [FromQuery] 对象 Asp.Net 核心、ModelBinding

[英]How to use DataMember Name for [FromQuery] object Asp.Net core, ModelBinding

对于 [FromBody] 参数,我可以使用DataMember.Name来设置属性的自定义名称,但它不适用于 [FromQuery]。 我想这取决于模型绑定

我想处理像?status=a&status=b&status=c

带有查询对象[FromQuery]MyQuery

[DataContract]
class MyQuery {
     [DataMember(Name = "status")
     public IReadOnlyList<string> Statuses { get; set; }
}

我可以这样做

class MyQuery {
     [FromQuery("status")
     public IReadOnlyList<string> Statuses { get; set; }
}

但我想避免来自AspNetCore模型依赖,有什么解决方案吗?

(有关于 Web API 2 的类似问题,但没有回答)

我没有找到使用标准属性的方法,所以我使用statuses名称,将自定义属性用于字符串集合

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
internal class StringCollectionAttribute : Attribute
{
}

并使用自定义模型绑定器

public class StringCollectionBinderProvider : IModelBinderProvider
{
    private static readonly Type BinderType = typeof(StringCollectionBinder);
    private static readonly Type ModelType = typeof(List<string>);

    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        var propertyAttributes = (context.Metadata as DefaultModelMetadata)?.Attributes.PropertyAttributes;

        var isStringCollection =
            propertyAttributes?.Any(x => x is StringCollectionAttribute) == true
            && context.Metadata.ModelType.IsAssignableFrom(ModelType);

        return isStringCollection ? new BinderTypeModelBinder(BinderType) : null;
    }
}

public class StringCollectionBinder : IModelBinder
{
    private const char ValueSeparator = ',';

    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        var modelName = bindingContext.ModelName;
        var valueCollection = bindingContext.ValueProvider.GetValue(modelName);

        if (valueCollection == ValueProviderResult.None)
        {
            return Task.CompletedTask;
        }

        bindingContext.ModelState.SetModelValue(modelName, valueCollection);

        var stringCollection = valueCollection.FirstValue;

        if (string.IsNullOrEmpty(stringCollection))
        {
            return Task.CompletedTask;
        }

        var collection = stringCollection.Split(ValueSeparator).ToList();
        bindingContext.Result = ModelBindingResult.Success(collection);
        return Task.CompletedTask;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM