3

An example of basic model binding to an object in ASP.NET MVC or the ASP.NET Web API might look like this (using C# as example):

public class MyModel
{
    public string value1 { get; set; } 
    public string value2 { get; set; }
}

public ValuesController : ApiController
{
    public HttpResponseMessage Post(MyModel model) { ... }
}

As long as the POST body looks like value1=somevalue&value2=someothervalue things map just fine.

But how do I handle a scenario where the post body contains parameter names that are disallowed as class property names, such as body-text=bla&...?

Robert
  • 353
  • 3
  • 14
  • Why do you have `body-text` in post body anyway? – artm Jun 16 '15 at 15:27
  • @artm Because that's what the service that is sending me a webhook is naming one of their parameters. It's an email service so they are referring the body of an email. It's just a name, it could be "foo-bar". The "body" in "body-text" has nothing to do with a post body. – Robert Jun 16 '15 at 15:31
  • 1
    possible duplicate of [ASP.NET MVC Model Binding with Dashes in Form Element Names](http://stackoverflow.com/questions/11173398/asp-net-mvc-model-binding-with-dashes-in-form-element-names) – Becuzz Jun 16 '15 at 19:35
  • 1
    Also, this might be worth looking at [http://stackoverflow.com/questions/3461365/using-a-dash-in-asp-mvc-parameters](http://stackoverflow.com/questions/3461365/using-a-dash-in-asp-mvc-parameters) – Becuzz Jun 16 '15 at 19:36

2 Answers2

1

You should be able to utilize data serialization attributes to help you with this:

[DataContract]
public class MyModel
{
    [DataMember(Name = "body-text")]
    public string value1 { get; set; } 
    public string value2 { get; set; }
}
peinearydevelopment
  • 11,042
  • 5
  • 48
  • 76
  • Whichever property I stick the attribute on comes up as null. I used your model example and sent the following post body `body-text=mybodytext&value2=bla`. value1 was null and value2 was "bla". – Robert Jun 16 '15 at 15:37
1

You can force Asp.Net to use the Newtonsoft.JSON deserializer by passing a JObject to your action, although it is a bit annoying to have to do it like this.

Then you can work with it as a JObject or call .ToObject<T>(); which will then honor the JsonProperty attribute.

// POST api/values
public IHttpActionResult Post(JObject content)
{
    var test = content.ToObject<MyModel>();
    // now you have your object with the properties filled according to JsonProperty attributes.
    return Ok();
}

MyModel example:

 public class MyModel
 {
     [JsonProperty(Name = "body-text")]
     public string value1 { get; set; } 

     public string value2 { get; set; }
 }
Ben Wilde
  • 5,552
  • 2
  • 39
  • 36