Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi Model Binding For Inherited Types

I'm looking to handle model binding for an inherited type in WebApi, and what I'm really looking to do is to handle the binding using the default model binding (other than selecting the type where it's unable to do so), but I'm missing something fundamental.

So say I have the types:

public abstract class ModuleVM
{
    public abstract ModuleType ModuleType { get; }
}

public class ConcreteVM : ModuleVM
{

}

Using an MVC controller, I would do something like this:

public class ModuleMvcBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        if (modelType == typeof(ModuleVM))
        {
            // Just hardcoding the type for simplicity
            Type instantiationType = typeof(ConcreteVM);
            var obj = Activator.CreateInstance(instantiationType);
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, instantiationType);
            bindingContext.ModelMetadata.Model = obj;
            return obj;
        }
        return base.CreateModel(controllerContext, bindingContext, modelType);
    }

}

[AttributeUsage( AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Struct | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class ModuleMvcBinderAttribute : CustomModelBinderAttribute
{
    public override IModelBinder GetBinder()
    {
        return new ModuleMvcBinder();
    }
}

Then use the attribute on the controller and all is well, and I'm leveraging the DefaultModelBinder for the real work and I'm essentially just providing the correct object instantiation.

So how do I do the same for the WebApi version?

If I use a custom model binder (e.g. Error implementing a Custom Model Binder in Asp.Net Web API), my problem is (I believe) that in the BindModel method I haven't found a good way to use the "standard" http binding once I instantiate the object. I can do it specifically for JSON (Deserialising Json to derived types in Asp.Net Web API) or XML (Getting my Custom Model bound to my POST controller) as suggested in other posts, but it seems to me that's defeating the point since web api should be seperating that, and is - it just doesn't know how to determine the type. (All concrete types naturally are handled just fine.)

Am I overlooking something obvious I should be directing the BindModel call to after instantiating the object?

like image 223
Gene Avatar asked Mar 20 '13 04:03

Gene


People also ask

What is model bindings in Web API?

Model Binding is the most powerful mechanism in Web API 2. It enables the response to receive data as per requester choice. i.e. it may be from the URL either form of Query String or Route data OR even from Request Body. It's just the requester has to decorate the action method with [FromUri] and [FromBody] as desired.

What is difference between FromQuery and FromBody?

[FromQuery] - Gets values from the query string. [FromRoute] - Gets values from route data. [FromForm] - Gets values from posted form fields. [FromBody] - Gets values from the request body.

How do we do parameter binding in Web API?

The item parameter is a complex type, so Web API uses a media-type formatter to read the value from the request body. To get a value from the URI, Web API looks in the route data and the URI query string. The route data is populated when the routing system parses the URI and matches it to a route.

What is the base controller for all Web API controllers to inherit from?

MVC controllers inherited from Controller ; Web API controllers inherited from ApiController .


1 Answers

Following is an example where I have inheritance in my types and after some settings (like decorating with KnownType attributes, required by Xml formatter's datacontractserializer) and TypeNameHandling setting on Json formatter, we can expect consistent behavior across both xml/json requests.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.SelfHost;

namespace Service
{
    class Service
    {
        private static HttpSelfHostServer server = null;
        private static string baseAddress = string.Format("http://{0}:9095/", Environment.MachineName);

        static void Main(string[] args)
        {
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);
            config.Routes.MapHttpRoute("Default", "api/{controller}/{id}", new { id = RouteParameter.Optional });
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects;

            try
            {
                server = new HttpSelfHostServer(config);
                server.OpenAsync().Wait();

                Console.WriteLine("Service listenting at: {0} ...", baseAddress);

                TestWithHttpClient("application/xml");

                TestWithHttpClient("application/json");

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception Details:\n{0}", ex.ToString());
            }
            finally
            {
                if (server != null)
                {
                    server.CloseAsync().Wait();
                }
            }
        }

        private static void TestWithHttpClient(string mediaType)
        {
            HttpClient client = new HttpClient();

            MediaTypeFormatter formatter = null;

            // NOTE: following any settings on the following formatters should match
            // to the settings that the service's formatters have.
            if (mediaType == "application/xml")
            {
                formatter = new XmlMediaTypeFormatter();
            }
            else if (mediaType == "application/json")
            {
                JsonMediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
                jsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects;

                formatter = jsonFormatter;
            }

            HttpRequestMessage request = new HttpRequestMessage();
            request.RequestUri = new Uri(baseAddress + "api/students");
            request.Method = HttpMethod.Get;
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mediaType));
            HttpResponseMessage response = client.SendAsync(request).Result;
            Student std = response.Content.ReadAsAsync<Student>().Result;

            Console.WriteLine("GET data in '{0}' format", mediaType);
            if (StudentsController.CONSTANT_STUDENT.Equals(std))
            {
                Console.WriteLine("both are equal");
            }

            client = new HttpClient();
            request = new HttpRequestMessage();
            request.RequestUri = new Uri(baseAddress + "api/students");
            request.Method = HttpMethod.Post;
            request.Content = new ObjectContent<Person>(StudentsController.CONSTANT_STUDENT, formatter);
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mediaType));
            Student std1 = client.SendAsync(request).Result.Content.ReadAsAsync<Student>().Result;

            Console.WriteLine("POST and receive data in '{0}' format", mediaType);
            if (StudentsController.CONSTANT_STUDENT.Equals(std1))
            {
                Console.WriteLine("both are equal");
            }
        }
    }

    public class StudentsController : ApiController
    {
        public static readonly Student CONSTANT_STUDENT = new Student() { Id = 1, Name = "John", EnrolledCourses = new List<string>() { "maths", "physics" } };

        public Person Get()
        {
            return CONSTANT_STUDENT;
        }

        // NOTE: specifying FromBody here is not required. By default complextypes are bound
        // by formatters which read the body
        public Person Post([FromBody] Person person)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState));
            }

            return person;
        }
    }

    [DataContract]
    [KnownType(typeof(Student))]
    public abstract class Person : IEquatable<Person>
    {
        [DataMember]
        public int Id { get; set; }

        [DataMember]
        public string Name { get; set; }

        public bool Equals(Person other)
        {
            if (other == null)
                return false;

            if (ReferenceEquals(this, other))
                return true;

            if (this.Id != other.Id)
                return false;

            if (this.Name != other.Name)
                return false;

            return true;
        }
    }

    [DataContract]
    public class Student : Person, IEquatable<Student>
    {
        [DataMember]
        public List<string> EnrolledCourses { get; set; }

        public bool Equals(Student other)
        {
            if (!base.Equals(other))
            {
                return false;
            }

            if (this.EnrolledCourses == null && other.EnrolledCourses == null)
            {
                return true;
            }

            if ((this.EnrolledCourses == null && other.EnrolledCourses != null) ||
                (this.EnrolledCourses != null && other.EnrolledCourses == null))
                return false;

            if (this.EnrolledCourses.Count != other.EnrolledCourses.Count)
                return false;

            for (int i = 0; i < this.EnrolledCourses.Count; i++)
            {
                if (this.EnrolledCourses[i] != other.EnrolledCourses[i])
                    return false;
            }

            return true;
        }
    }
}
like image 89
Kiran Avatar answered Oct 07 '22 10:10

Kiran