的WebAPI模型绑定对于继承的类型 [英] WebApi Model Binding For Inherited Types

查看:146
本文介绍了的WebAPI模型绑定对于继承的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找处理模型绑定在的WebAPI继承类型,我真正希望做的是处理使用默认的模型绑定(不是选择它是无法在其他类型这样做)的结合,但我失去了一些东西根本。

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.

所以说,我有类型:

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

public class ConcreteVM : ModuleVM
{

}

使用MVC控制器,我会做这样的事情:

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();
    }
}

然后使用控制器上的属性,一切都很好,而且我充分利用DefaultModelBinder的实际工作,我基本上只是提供正确的对象实例化。

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.

所以,我该怎么办了的WebAPI的版本一样吗?

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

如果我使用一个自定义模型粘合剂(例如<一个href=\"http://stackoverflow.com/questions/13805915/error-implementing-a-custom-model-binder-in-asp-net-web-api\">Error实现自定义模型绑定在Asp.Net的Web API ),我的问题是(我相信),在BindModel方法我还没有发现使用标准http绑定,一旦我实例化对象的好方法。我能做到这一点专门为JSON(<一个href=\"http://stackoverflow.com/questions/12638741/deserialising-json-to-derived-types-in-asp-net-web-api\">Deserialising JSON来在Asp.Net的Web API 派生类型)或XML(<一个href=\"http://stackoverflow.com/questions/10643590/getting-my-custom-model-bound-to-my-post-controller\">Getting我的自定义模式绑定到我POST控制器),如其他职位的建议,但在我看来,战胜的,因为网页API应该是分隔条件的点,就是 - 它只是不知道如何确定类型。 (所有具体类型自然的处理就好了。)

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.)

我俯瞰明显的东西,我应该实例化对象后指挥BindModel调用?

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

推荐答案

以下是JSON的,我有我的类型和经过一些设置继承一个例子(像KnownType装饰属性,被XML格式的DataContractSerializer的需要)和TypeNameHandling设置格式化,我们可以期待在这两个XML / JSON请求一致的行为。

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;
        }
    }
}

这篇关于的WebAPI模型绑定对于继承的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆