WebAPI Custom Model binding of complex abstract object

扶醉桌前 提交于 2019-11-29 02:23:30

After some research I discovered that metadata providers don't exist within WebAPI and in order to bind to complex abstract objects you have to write your own.

I started by writing a new model binding method, with the use of a custom type name JSon serializer and finally I updated my endpoint to use the custom binder. It's worth noting the following will only work with requests in the body, you will have to write something else for requests in the header. I would suggest a read of chapter 16 of Adam Freeman's Expert ASP.NET Web API 2 for MVC Developers and complex object binding.

I was able to serialize my object from the body of the request using the following code.

WebAPI configuration

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Services.Insert(typeof(ModelBinderProvider), 0,
            new SimpleModelBinderProvider(typeof(RecordCollection), new JsonBodyModelBinder<RecordCollection>()));
    }
}

Custom model binder

public class JsonBodyModelBinder<T> : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext,
        ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(T))
        {
            return false;
        }

        try
        {
            var json = ExtractRequestJson(actionContext);

            bindingContext.Model = DeserializeObjectFromJson(json);

            return true;
        }
        catch (JsonException exception)
        {
            bindingContext.ModelState.AddModelError("JsonDeserializationException", exception);

            return false;
        }


        return false;
    }

    private static T DeserializeObjectFromJson(string json)
    {
        var binder = new TypeNameSerializationBinder("");

        var obj = JsonConvert.DeserializeObject<T>(json, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Auto,
            Binder = binder
        });
        return obj;
    }

    private static string ExtractRequestJson(HttpActionContext actionContext)
    {
        var content = actionContext.Request.Content;
        string json = content.ReadAsStringAsync().Result;
        return json;
    }
}

Custom Serialization binding

public class TypeNameSerializationBinder : SerializationBinder
{
    public string TypeFormat { get; private set; }

    public TypeNameSerializationBinder(string typeFormat)
    {
        TypeFormat = typeFormat;
    }

    public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
    {
        assemblyName = null;
        typeName = serializedType.Name;
    }

    public override Type BindToType(string assemblyName, string typeName)
    {
        string resolvedTypeName = string.Format(TypeFormat, typeName);

        return Type.GetType(resolvedTypeName, true);
    }
}

End point definition

    [HttpPost]
    public void Post([ModelBinder(BinderType = typeof(JsonBodyModelBinder<RecordCollection>))]RecordCollection recordCollection)
    {
    }

The TypeNameSerializationBinder class is not necessary anymore as well as the WebApiConfig configuration.

First, you need to create enum for record type:

public enum ResourceRecordTypeEnum
{
    a,
    b
}

Then, change your "Type" field in ResourceRecord to be the enum we just created:

public abstract class ResourceRecord
{
    public abstract ResourceRecordTypeEnum Type { get; }
}

Now you should create these 2 classes:

Model Binder

public class ResourceRecordModelBinder<T> : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(T))
            return false;

        try
        {
            var json = ExtractRequestJson(actionContext);
            bindingContext.Model = DeserializeObjectFromJson(json);
            return true;
        }
        catch (JsonException exception)
        {
            bindingContext.ModelState.AddModelError("JsonDeserializationException", exception);
            return false;
        }
    }

    private static T DeserializeObjectFromJson(string json)
    {
        // This is the main part of the conversion
        var obj = JsonConvert.DeserializeObject<T>(json, new ResourceRecordConverter());
        return obj;
    }

    private string ExtractRequestJson(HttpActionContext actionContext)
    {
        var content = actionContext.Request.Content;
        string json = content.ReadAsStringAsync().Result;
        return json;
    }
}

Converter class

public class ResourceRecordConverter : CustomCreationConverter<ResourceRecord>
{
    private ResourceRecordTypeEnum _currentObjectType;

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var jobj = JObject.ReadFrom(reader);
        // jobj is the serialized json of the reuquest
        // It pulls from each record the "type" field as it is in requested json,
        // in order to identify which object to create in "Create" method
        _currentObjectType = jobj["type"].ToObject<ResourceRecordTypeEnum>();
        return base.ReadJson(jobj.CreateReader(), objectType, existingValue, serializer);
    }

    public override ResourceRecord Create(Type objectType)
    {
        switch (_currentObjectType)
        {
            case ResourceRecordTypeEnum.a:
                return new ARecord();
            case ResourceRecordTypeEnum.b:
                return new BRecord();
            default:
                throw new NotImplementedException();
        }
    }
}

Controller

[HttpPost]
public void Post([ModelBinder(BinderType = typeof(ResourceRecordModelBinder<RecordCollection>))] RecordCollection recordCollection)
{ 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!