1 回答

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超3個(gè)贊
為什么屬性訪問(wèn)修飾符只影響原始類型的屬性?
對(duì)于 Asp.Net Core ModelBinder,它將通過(guò)下面的ComplexTypeModelBinder代碼檢查該屬性是否為私有訪問(wèn)設(shè)置器:
protected virtual object CreateModel(ModelBindingContext bindingContext)
{
? ? if (bindingContext == null)
? ? {
? ? ? ? throw new ArgumentNullException(nameof(bindingContext));
? ? }
? ? // If model creator throws an exception, we want to propagate it back up the call stack, since the
? ? // application developer should know that this was an invalid type to try to bind to.
? ? if (_modelCreator == null)
? ? {
? ? ? ? // The following check causes the ComplexTypeModelBinder to NOT participate in binding structs as
? ? ? ? // reflection does not provide information about the implicit parameterless constructor for a struct.
? ? ? ? // This binder would eventually fail to construct an instance of the struct as the Linq's NewExpression
? ? ? ? // compile fails to construct it.
? ? ? ? var modelTypeInfo = bindingContext.ModelType.GetTypeInfo();
? ? ? ? if (modelTypeInfo.IsAbstract || modelTypeInfo.GetConstructor(Type.EmptyTypes) == null)
? ? ? ? {
? ? ? ? ? ? var metadata = bindingContext.ModelMetadata;
? ? ? ? ? ? switch (metadata.MetadataKind)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? case ModelMetadataKind.Parameter:
? ? ? ? ? ? ? ? ? ? throw new InvalidOperationException(
? ? ? ? ? ? ? ? ? ? ? ? Resources.FormatComplexTypeModelBinder_NoParameterlessConstructor_ForParameter(
? ? ? ? ? ? ? ? ? ? ? ? ? ? modelTypeInfo.FullName,
? ? ? ? ? ? ? ? ? ? ? ? ? ? metadata.ParameterName));
? ? ? ? ? ? ? ? case ModelMetadataKind.Property:
? ? ? ? ? ? ? ? ? ? throw new InvalidOperationException(
? ? ? ? ? ? ? ? ? ? ? ? Resources.FormatComplexTypeModelBinder_NoParameterlessConstructor_ForProperty(
? ? ? ? ? ? ? ? ? ? ? ? ? ? modelTypeInfo.FullName,
? ? ? ? ? ? ? ? ? ? ? ? ? ? metadata.PropertyName,
? ? ? ? ? ? ? ? ? ? ? ? ? ? bindingContext.ModelMetadata.ContainerType.FullName));
? ? ? ? ? ? ? ? case ModelMetadataKind.Type:
? ? ? ? ? ? ? ? ? ? throw new InvalidOperationException(
? ? ? ? ? ? ? ? ? ? ? ? Resources.FormatComplexTypeModelBinder_NoParameterlessConstructor_ForType(
? ? ? ? ? ? ? ? ? ? ? ? ? ? modelTypeInfo.FullName));
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? _modelCreator = Expression
? ? ? ? ? ? .Lambda<Func<object>>(Expression.New(bindingContext.ModelType))
? ? ? ? ? ? .Compile();
? ? }
? ? return _modelCreator();
}
為什么當(dāng)參數(shù)屬性設(shè)置為 FromForm 時(shí)會(huì)出現(xiàn)這種情況,而設(shè)置為 FromBody 時(shí)不會(huì)出現(xiàn)這種情況
對(duì)于FromBody,它用于JsonInputFormatter從正文請(qǐng)求中綁定模型,它用于JsonConvert.DeserializeObject反序列化對(duì)象并Newtonsoft.Json支持從 json 字符串中反序列化包含私有 setter 的對(duì)象。
- 1 回答
- 0 關(guān)注
- 155 瀏覽
添加回答
舉報(bào)