csharp Web API的抽象模型绑定

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp Web API的抽象模型绑定相关的知识,希望对你有一定的参考价值。

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;

public class AbstractMediaTypeFormatter : FormUrlEncodedMediaTypeFormatter
{
	public AbstractMediaTypeFormatter()
	{
		SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
	}

	public override bool CanReadType(Type type)
	{
		return type.IsAbstract;
	}

	public async override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
	{
		object result = null;

		await Task.Run(() => {
			using (StreamReader reader = new StreamReader(readStream)) {
				string json = reader.ReadToEnd();

				Type typeToCreate = GetType(json, type);
				if (typeToCreate != null)
					result = JsonConvert.DeserializeObject(json, typeToCreate);
			}
		});

		return result;
	}

	// helpers
	private static ICustomTypeDescriptor GetTypeDescription(Type type)
	{
		return new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);
	}

	private static Type GetType(string json, Type abstractType) {
		List<string> jsonProperties = JObject.Parse(json)
			.Properties()
			.Select(x => x.Name)
			.ToList();

		return Assembly.GetExecutingAssembly()
			.GetTypes()
			.Where(x => x.IsSubclassOf(abstractType))
			.Select(x => new {
				Type = x,
				Percentage = GetSuccessPercentage(x, jsonProperties)
			})
			.Where(x => x.Percentage >= 25)
			.OrderByDescending(x => x.Percentage)
			.Select(x => x.Type)
			.FirstOrDefault();
	}

	private static int GetSuccessPercentage(Type type, List<string> jsonProperties)
	{
		List<string> properties = GetTypeDescription(type).GetProperties().Cast<PropertyDescriptor>().Select(x => x.Name).ToList();

		int mappableProperties = jsonProperties.Count(x => properties.Any(y => y.Equals(x, StringComparison.InvariantCultureIgnoreCase)));

		return (int)(((decimal)mappableProperties / jsonProperties.Count) * 100m);
	}
}

以上是关于csharp Web API的抽象模型绑定的主要内容,如果未能解决你的问题,请参考以下文章

Web Api模型绑定和多态继承

csharp web api自定义模型过滤

csharp 操作筛选器自动返回Web API的模型状态错误

细说 Web API参数绑定和模型绑定

Web Api 模型绑定 一

来自json的web api 2绑定模型