问题
Implementing a webhook in Asp.Net Core which is POSTed to with application/x-form-urlencoded
data - it's receiving data in a format that is designed to be easily processable in PHP w/ the $_POST
variable (nested associative array) - the form fields look like
foo
bar[barf]
baz[bat][bark]
baz[bat][bant]
Is there a nice (elegant and little code required) way to wire up the Asp.NET Core model binding to handle the nested structure here? i.e. when the webhook gets POSTed to, we parse a C# POCO -
something like
class RootDto {
public string Foo {get; set;}
public Bar Bar {get; set;}
public Baz Baz {get; set;}
public class Bar {
public string Barf {get; set;}
}
public class Baz {
public Bat Bat {get; set;}
public class Bat {
public string Bark {get; set;}
public string Bant {get; set;}
}
}
}
The POST body looks something like the following:
foo=somevalue&bar%5Bbarf%5D=anothervalue&baz%5Bbat%5D%5Bbark%5D=123.0&baz%5Bbat%5D%5Bbant%5D=5000
i.e.
foo=somevalue&bar[barf]=anothervalue&baz[bat][bark]=123.0&baz[bat][bant]=5000
Also, what's the low-friction way to set up a type-converter for one of these fields (e.g. assume the field "Foo" comes in as a string but we want to parse it into a struct)?
Note that I don't have control of the shape or encoding of the data coming in from the webhook (e.g. I can't request they just send me JSON).
回答1:
Request body
Content-Type: application/x-www-form-urlencoded
foo=somevalue&bar%5Bbarf%5D=anothervalue&baz%5Bbat%5D%5Bbark%5D=123.0&baz%5Bbat%5D%5Bbant%5D=5000
It just works.... I have plain .net core project and controller looks like
public IActionResult Post([FromForm] RootDto request)
{
return Ok(request);
}
Btw your root class seems to be wrong I've changed to make it work
public class RootDto {
public string Foo {get; set;}
public BarClass Bar {get; set;}
public BazClass Baz {get; set;}
public class BarClass {
public string Barf {get; set;}
}
public class BazClass {
public BatClass Bat {get; set;}
public class BatClass {
public string Bark {get; set;}
public string Bant {get; set;}
}
}
}
来源:https://stackoverflow.com/questions/48875360/mapping-nested-x-form-urlencoded-data-to-dto-in-asp-net-core