0

I have the following class that I use in my WebApi2 service.

[DataContract()]
public class TokenRequest
{
    [Required]
    [DataMember(Name = "last_name")]
    public String LastName { get; set; }

    [Required]
    [DataMember(Name = "badge_number")]
    public String BadgeNumber { get; set; }
}

As you can see the class's properties are aliased with [DataMember(Name = "...")]

Using the following controller

[Route("Service/GetToken")]
[HttpPost]
public IHttpActionResult GetToken(TokenRequest request) { ... }

I had hoped to get a TokenRequest object with the following POST body

last_name=Stillwell&badge_number=0000

However, both request.LastName and request.BadgeNumber are null.

Now, if I make the request like so:

LastName=Stillwell&BadgeNumber=0000

request.LastName and request.BadgeNumber will have the correct values. Why isn't [DataMember(Name = "...")] pulling in my values when I use last_name or badge_number?

Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
  • Possible duplicate of [Web API form-urlencoded binding to different property names](http://stackoverflow.com/questions/20997913/web-api-form-urlencoded-binding-to-different-property-names) – Federico Dipuma May 08 '17 at 21:02
  • @Dayan, I am. Hence the `[HttpPost]` attribute on the controller. – Chris Stillwell May 08 '17 at 21:22
  • Without seeing more it is hard to tell, but my guess is that the application is using the Newtonsoft library to handle it's de/serialization of the JSON objects in which case you would want to use the JsonProperty attribute, for instance `[JsonProperty("last_name")]` on the LastName property of the TokenRequest class; – peinearydevelopment May 09 '17 at 17:05
  • @peinearydevelopment a previous (now deleted) answer suggested that. However, the result was the same. I received null values from the request. – Chris Stillwell May 09 '17 at 17:39
  • did you try making it with the POST body like this: `{"last_name":"Stillwell","badge_number"="000"}`? – peinearydevelopment May 10 '17 at 13:18

1 Answers1

0

I was able to resolve this by returning TokenRequest in the Controller.

[Route("Service/GetToken")]
[HttpPost]
public TokenRequest GetToken(TokenRequest request) { ... }

Then, in my WebApiConfig.cs file I added the following

var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

This returns JSON instead of XML. See: How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77