Raw POST data deserialization using C#/.net (bind to complex model) like in modelbinder of MVC/webApi

本小妞迷上赌 提交于 2019-12-24 12:05:18

问题


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

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

to my complex object

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

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.


回答1:


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.

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


来源:https://stackoverflow.com/questions/48457738/raw-post-data-deserialization-using-c-net-bind-to-complex-model-like-in-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!