4

I've got one method, which take a model [AccountLinkRequest] as a parameter with url-encoded data. It's uses Json.NET by default, and also, I can't use the setting UseDataContractJsonSerializer = true cause I have generic output response model (in other methods)

[HttpPost]
public SomeResponse Link(AccountLinkRequest request)
{
    if (request.CustomerId == null)
        throw new Exception("Deserialization error here, pls help!");

    // other actions
}

Here is my model class:

[DataContract]
[JsonObject]
public class AlertAccountLinkRequest
{
    [DataMember(Name = "id")]
    public string id { get; set; }

    [DataMember(Name = "customer_id")]
    [JsonProperty("customer_id")]
    public string CustomerId { get; set; }
}

The problem: request.CustomerId is allways null. The request is pretty simple:

web_service_URL/link?customer_id=customer_id&id=id (url-encoded)

if I use Customer_Id instead of CustomerId, everything will be fine, but I'm on a jedy-way. Thank you!

EvgeniyK
  • 377
  • 3
  • 12

1 Answers1

1

There is not a simple answer how to achieve that. For more details please read this:

How to bind to custom objects in action signatures in MVC/WebAPI

Summary:

  1. Manually call the parse function inside of your Action
  2. Use a TypeConverter to make the complex type be simple
  3. Use a custom model binder

So, if you for instance create your 'SmartBinder' which is able to consume some attributes, you can get what you want. Out fo the box there is no functionality for that, just the naming conventions...

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Radim, thank you for a reply. I still can't believe that DataMember / JsonProperty are not serving it. It's the same as with ORM we couldn't define own property names instead of using column names. Btw there was Json.NET 5.0+ update, but nothing changed – EvgeniyK Jun 10 '13 at 18:26
  • 1
    In this case, we are talking about ModelBinder. We want to change a query (part of the query string) to be converted into an object. Only the 3 above mentioned methods are available. What you are talking about, is parsing of the BODY. And for this, we use MediaFormatters. And these could be very powerful, tweakable, extandable... So there is the biggest difference. Query vs BODY. Request-body can contain a JSON a Json attribute (e.g. `[JsonProperty(PropertyName='')]`) could be used ... not in this case. bad news I know ;( – Radim Köhler Jun 11 '13 at 02:45