1

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.

Nigrimmist
  • 10,289
  • 4
  • 52
  • 53
  • It looks like you will have to manually parse out the site[domain][id] parameter. You may have to create your ComplObject class, and then assign each of the properties a value (coming from request parameters) – Anthony McGrath Jan 26 '18 at 08:18
  • Have a look https://stackoverflow.com/questions/9817591/convert-querystring-from-to-object Not sure if there's a ready-made solution, but you can convert to Json first, then deserialize https://stackoverflow.com/questions/12428947/how-do-i-convert-a-querystring-to-a-json-string – Ivan Zaruba Jan 26 '18 at 08:21
  • @AnthonyMcGrath i need a generic solution, manually parse it is a bad solution in my case – Nigrimmist Jan 26 '18 at 08:47
  • @IvanZaruba i need Inverted soultion, not model to url data, so your link, unfortunately, useless – Nigrimmist Jan 26 '18 at 08:49
  • What about an extension method of `HttpRequest` who parse POST parameter and return `ComplObject` ? Is what you need ? – GGO Jan 26 '18 at 09:07

1 Answers1

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)
{
...
}
Troopers
  • 5,127
  • 1
  • 37
  • 64