4

I am trying to figure out a way to map POSTED form parameters that have hyphens in them to a WEB-API method that takes a complex object.

Some context:

We are using Mailgun to forward a processed email to our own custom Web API Controller method.

Mailgun POSTS to our API and some of the parameters it uses have hyphens in them - for example: body-plain.

My C# complex model will have a property to match in Pascal Case (can't use hyphens in property names)

so if these parameters are generated by Mailgun and posted to our WEB API controller:

   from
   subject
   body-plain
   body-stripped
   timestamp

and our complex object looks like this:

public class Response{
   public string From{get; set;}
   public string Subject{get; set;}
   public string BodyPlain{get; set;}    
   public string BodyStripped{get; set;
   public int Timestamp{get; set;}
}

Then From, Subject, and Timestamp all map correctly - but BodyPlain and BodyStripped do not - they are null since the model binding can't translate the hyphenated parameters to Camelcase.

Is there a way to do this?

I have seen some posts referring to different ways to achieve this with MVC but we are not using MVC, just strictly WEB API.

Pacificoder
  • 1,581
  • 4
  • 18
  • 32

2 Answers2

1

You can use the Request object in the controller, which will make the parameters available key/value style.

In the case of Mailgun forwarding (which was the same problem I ran into), the Request.ReadFormAsync() method will expose the IFormCollection, from which you can access the parameters you need via:

IFormCollection.TryGetValue("my-parameter", out StringValues myParameter)
Bryan
  • 2,870
  • 24
  • 39
  • 44
0

Since the parameters are sent through form submission and not JSON, using [JsonProperty(PropertyName = "my-param")] won't help and you'll have to resort to having your action receiving a parameter of type FormDataCollection and then inside your action you'll map it to your complex object. An alternative is to implement a custom model binder.

In this post there are details about those two options.

BornToCode
  • 9,495
  • 9
  • 66
  • 83