【发布时间】:2015-08-27 21:41:03
【问题描述】:
所以现有的问题都没有回答这个问题。
我已经为 web api 2 实现了一个自定义模型绑定器,如下所示
public class AModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(Type modelType)
{
return modelType == typeof(A) ? new AdAccountModelBinder() : null;
}
}
public class AModelBinder : DefaultModelBinder
{
private readonly string _typeNameKey;
public AModelBinder(string typeNameKey = null)
{
_typeNameKey = typeNameKey ?? "type";
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var providerResult = bindingContext.ValueProvider.GetValue(_typeNameKey);
if (providerResult != null)
{
var modelTypeName = providerResult.AttemptedValue;
SomeEnum type;
if (!Enum.TryParse(modelTypeName, out type))
{
throw new InvalidOperationException("Bad Type. Does not inherit from AdAccount");
}
Type modelType;
switch (type)
{
case SomeEnum.TypeB:
modelType = typeof (B);
break;
default:
throw new InvalidOperationException("Bad type.");
}
var metaData =
ModelMetadataProviders.Current
.GetMetadataForType(null, modelType);
bindingContext.ModelMetadata = metaData;
}
// Fall back to default model binding behavior
return base.BindModel(controllerContext, bindingContext);
}
模型定义如下 -
Public class A {}
Public Class B : A {}
Web Api Action 如下 -
[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/a")]
[System.Web.Http.Authorize]
public async Task<HttpResponseMessage> Add([ModelBinder(typeof(AModelBinderProvider))]Models.A a)
{}
在 Application_Start 中将我的提供者注册为绅士 -
var provider = new AdAccountModelBinderProvider();
ModelBinderProviders.BinderProviders.Add(provider);
我的自定义 Binder 仍然拒绝启动。
我迷路了。我错过了什么?
【问题讨论】:
-
什么是
AdAccountModelBinder?你实现了AModelBinder?
标签: c# .net asp.net-mvc asp.net-web-api model-binding