0

I am writing a Web Api service to receive data from call back from a client's API. Since they specify their incoming services as receiving JSON, I have assumed that their callbacks would also post the data in JSON format. However, when it comes to testing my API, I have discovered that they are actually posting form data.

This isn't a problem in itself, as the API accepts POST data in several formats. However, when accepting the data as JSON, I can do something like this:

public IHttpActionResult Post(Message message)
{
    ...
}

public class Message 
{
    [JsonProperty("name")]
    public string NameParameter { get; set; }
}

This allow me to post json such as { "name": "Dave" } and refer to the parameter in my handler as message.NameParameter.

However, when the data is received as forms data (application/x-www-form-urlencoded), for example name=Dave, the JsonProperty attributes do nothing (hardly surprising given the attribute name), and message.NameParameter ends up as null.

Of course, I could just change the property name in the Message class to match the POST parameter name, but in certain cases, the names of the POST parameters do not conform to our coding standards, so I would prefer a way to specify the binding via an attribute, in the same way JSON data is handled.

7
  • How are you submitting the form? If this is an Ajax request, could you not format your data as JSON before you send it to the server? Commented Jun 1, 2015 at 15:13
  • Why not just rename the model property to name? Commented Jun 1, 2015 at 15:15
  • I'm not actually submitting the form data, I am writing the web service to receive the form data from a third party. I was originally expecting to get JSON posted to it (hence the use of JsonProperty), but didn't discover that it is actually old-school forms data until testing. Commented Jun 1, 2015 at 15:16
  • In this example, it would be acceptable to change it to name, however, this is just an example. The actual forms data and property names are different, and the names in the forms data do not conform to our coding standards (using Hungarian notation, and abbreviations for starters). If there are no better ways of doing it, I may have to bite the bullet and accept that these are the property names I will have to use, but prefer not to unless absolutely necessary. Commented Jun 1, 2015 at 15:18
  • 2
    This looks like the solution to your problem: stackoverflow.com/a/4316327/894792 Commented Jun 1, 2015 at 15:23

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.