Web.Api deserialization error for a model parameter with a different name

I have one method that takes the [AccountLinkRequest] model as a parameter with data encoded in url. It uses Json.NET by default, and also, I cannot use the UseDataContractJsonSerializer = true reason parameter. I have an output response model (in other ways).

[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; } } 

Problem: request.CustomerId is always 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 in a traffic jam. Thanks!

+4
source share
1 answer

There is no simple answer how to achieve this. For more information, please read the following:

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

Summary:

  • Manually call the parsing function inside the action
  • Use TypeConverter to simplify a complex type.
  • Use custom connectivity

So, if you, for example, create your own "SmartBinder", which can consume some attributes, you can get what you want. There are no functions for the box for this, just a naming convention ...

+1
source

Source: https://habr.com/ru/post/1485422/


All Articles