I have a .Net Core Web API. It automatically maps models when the model properties match the request body. For example, if you have this class:
public class Package { public string Carrier { get; set; } public string TrackingNumber { get; set; } }
It would correctly bind it to a POST endpoint if the request body is the following JSON:
{ carrier: "fedex", trackingNumber: "123123123" }
What I need to do is specify a custom property to map. For example, using the same class above, I need to be able to map to JSON if the TrackingNumber comes in as tracking_number
.
How do I do that?
Show activity on this post. MakeUser method in the User controller for creating a username and password. UserParameter class for sending the parameters as an object. RunAsync method in console client.
The item parameter is a complex type, so Web API uses a media-type formatter to read the value from the request body. To get a value from the URI, Web API looks in the route data and the URI query string. The route data is populated when the routing system parses the URI and matches it to a route.
The [FromUri] attribute is prefixed to the parameter to specify that the value should be read from the URI of the request, and the [FromBody] attribute is used to specify that the value should be read from the body of the request.
[FromForm] - Gets values from posted form fields. [FromBody] - Gets values from the request body.
TejSoft's answer does not work in ASP.NET Core 3.0 Web APIs by default.
Starting in 3.0, the ASP.NET Core Json.NET (Newtonsoft.Json) sub-component is removed from the ASP.NET Core shared framework. It is announced that, "Json.NET will continue to work with ASP.NET Core, but it will not be in the box with the shared framework." The newly added Json Api claimed to be specifically geared for high-performance scenarios.
Use JsonPropertyName
attribute to set a custom property name:
using System.Text.Json.Serialization; public class Package { [JsonPropertyName("carrier")] public string Carrier { get; set; } [JsonPropertyName("tracking_number")] public string TrackingNumber { get; set; } }
Change your package class and add JsonProperty decoration for each field you wish to map to a different json field.
public class Package { [JsonProperty(PropertyName = "carrier")] public string Carrier { get; set; } [JsonProperty(PropertyName = "trackingNumber")] public string TrackingNumber { get; set; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With