7

For application/json or application/xml I can use DataContract for a custom property name binding:

[HttpPost]
public string Method([FromBody]Model request)
{
}

[DataContract]
public class Model
{
    [DataMember(Name="custom_name")]
    public string CustomName { get; set; }
}

How can I use DataContract or something else for application/x-www-form-urlencoded?

skuntsel
  • 11,484
  • 11
  • 43
  • 66
  • 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) – Toine Seiter Feb 13 '17 at 12:17

3 Answers3

0

There is a built-in FormUrlEncodedMediaTypeFormatter implementation for form-urlencoded that you can use. It should work against any POCO class (Your data contract should work as well but it would ignore the DataContract attributes),

http://msdn.microsoft.com/en-us/library/system.net.http.formatting.formurlencodedmediatypeformatter(v=vs.108).aspx

Make sure you have that media type formatter configured in your web api.

Pablo Cibraro
  • 3,729
  • 2
  • 24
  • 16
0

Here's an MSDN post on setting the DataContractFormat: http://blogs.msdn.com/b/endpoint/archive/2011/05/15/using-datacontracts-with-wcf-web-api.aspx

The MediaTypeFormatterCollection class contains FormUrlEncodedFormatter. You could try the above post to set your DataContractSerializer.

MichaelJCox
  • 756
  • 7
  • 17
0

It's an old post but maybe this could helps other people. Here is a solution with ModelBinder and AliasAttribute to do this kind of code :

[ModelBinder(typeof(AliasBinder))]
public class MyModel
{
    [Alias("state")]
    public string Status { get; set; }
}

Hope this helps :)

Toine Seiter
  • 427
  • 4
  • 20
  • Please don't add [the same answer](http://stackoverflow.com/a/42203608/4687348) to multiple questions. Answer the best one and flag the rest as duplicates. See [Is it acceptable to add a duplicate answer to several questions?](http://meta.stackexchange.com/q/104227/347985) – FelixSFD Feb 13 '17 at 12:09