问题
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