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&...?

4
  • Why do you have body-text in post body anyway? Commented Jun 16, 2015 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. Commented Jun 16, 2015 at 15:31
  • 1
    possible duplicate of ASP.NET MVC Model Binding with Dashes in Form Element Names Commented Jun 16, 2015 at 19:35
  • 1
    Also, this might be worth looking at http://stackoverflow.com/questions/3461365/using-a-dash-in-asp-mvc-parameters Commented Jun 16, 2015 at 19:36

2 Answers 2

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; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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".
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; }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.