Raw POST data deserialization using C#/.net (bind

2019-08-13 23:50发布

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条回答
Bombasti
2楼-- · 2019-08-14 00:34

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)
{
...
}
查看更多
登录 后发表回答