因此,现有问题都无法回答这个问题。

我已经为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操作如下-

        [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);


我的自定义活页夹仍然拒绝启动。

我迷路了。我想念什么?

最佳答案

您需要实现IModelBinder接口:

看下面的自定义示例:

public class MyModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        try
        {
            bindingContext.Model = new TestClass();

            //following lines invoke default validation on model
            bindingContext.ValidationNode.ValidateAllProperties = true;
            bindingContext.ValidationNode.Validate(actionContext);

            return true;
        }
        catch
        {
            return false;
        }
    }
}



设置模型活页夹


有几种设置模型绑定器的方法。首先,您可以向参数添加[ModelBinder]属性。

public HttpResponseMessage Get([ModelBinder(typeof(MyModelBinder))] TestClass objTest)


您还可以向类型添加[ModelBinder]属性。 Web API将为该类型的所有参数使用指定的模型绑定器。

[ModelBinder(typeof(MyModelBinder))]
public class TestClass
{
    // ....
}


最后,您可以将模型绑定程序提供程序添加到HttpConfiguration中。模型绑定器提供程序只是创建模型绑定器的工厂类。您可以通过派生ModelBinderProvider类来创建提供程序。但是,如果模型联编程序处理的是单个类型,则使用为此目的而设计的内置SimpleModelBinderProvider会更容易。以下代码显示了如何执行此操作。

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var provider = new SimpleModelBinderProvider(
            typeof(TestClass), new MyModelBinder());
        config.Services.Insert(typeof(ModelBinderProvider), 0, provider);

        // ...
    }
}


对于模型绑定提供程序,您仍然需要向参数添加[ModelBinder]属性,以告知Web API它应该使用模型绑定程序而不是媒体类型格式化程序。但是现在您无需在属性中指定模型绑定程序的类型:

public HttpResponseMessage Get([ModelBinder] TestClass objTestClass) { ... }

关于c# - 自定义模型活页夹未启动Web API 2,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32259920/

10-10 21:59