使用C#/.net(绑定到复杂模型)进行原始POST数据反序列化,例如在MVC/webApi的modelbinder中 [英] Raw POST data deserialization using C#/.net (bind to complex model) like in modelbinder of MVC/webApi

查看:289
本文介绍了使用C#/.net(绑定到复杂模型)进行原始POST数据反序列化,例如在MVC/webApi的modelbinder中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用任何现成的通用解决方案来转换带有POST数据的字符串,例如:

I would like to have any ready generic solution to convert string with POST data like :

"id=123&eventName=eventName&site[domain][id]=123"

到我的复杂对象

public class ComplObject {
   public int id {get;set;}
   public string eventName {get;set;}
   public siteClass site{get;set;}
}

public class siteClass {       
   public domainClass domain {get;set;}       
}

public class domainClass {
   public int id {get;set;}       
}

允许访问asp.net MVC参考. 看起来,就像我需要独立的formdata绑定程序一样,但是我找不到任何工作库/代码来处理它.

Access to asp.net MVC reference is allowed. Looks,like i need standalone formdata binder, but i cannot find any work library/code to handle it.

推荐答案

您需要通过覆盖

You need to implement your custom http parameter binding by overriding the HttpParameterBinding class. Then create a custom attribute to use it on your web API.

从json内容读取参数的示例:

Example with a parameter read from json content :

CustomAttribute :

/// <summary>
/// Define an attribute to define a parameter to be read from json content
/// </summary>
[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]
public class FromJsonAttribute : ParameterBindingAttribute
{
    public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
    {
        return new JsonParameterBinding(parameter);
    }
}

ParameterBinding:

/// <summary>
/// Defines a binding for a parameter to be read from the json content
/// </summary>
public class JsonParameterBinding : HttpParameterBinding
{
...Here your deserialization logic
}

WepAPi

[Route("Save")]
[HttpPost]
public HttpResponseMessage Save([FromJson] string name,[FromJson] int age,[FromJson] DateTime birthday)
{
...
}

这篇关于使用C#/.net(绑定到复杂模型)进行原始POST数据反序列化,例如在MVC/webApi的modelbinder中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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