Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass multiple complex arguments in json post request to asp.net WebApi

Assuming a ApiController with an action having multiple arguments:

[HttpPost]
public void AddAddress( Person person, Address address, int simple )

Or something like that. Now I try to send a post request with content type application/json and json like this:

{
  person: {...}, address: {..}, simple: 1
}

just assume it's valid json ;)

or in a json array like this: [person, address, simple]

But WebApi won't recognize this and tell me it can't find the action, as it doesn't support multiple parameters in a json request.

I'm doing this from a C# client using HttpClient and we'd like to do post requests using json. I wanted to use the WebApi.Client package, which provides several useful extensions to the HttpClient, but we have a portable library project(which webapi client doesn't support).

How would I go about supporting this feature?

I tried to use an custom ActionFilter, which never get's to run as it can't find the action beforehand. I tried MediaTypeFormatter which doesn't know the context and the arguments, and also I tried ModelBinder, which also seems only on a per argument basis and doesn't always get executed.

Thanks!

like image 238
sharp johnny Avatar asked Jul 19 '26 09:07

sharp johnny


1 Answers

The built-in parameter binding strategy in ASP.NET Web API with formatters only supports a single complex argument mapped to the request body. In your case, you are trying to map at least two complex arguments. The simplest solution without extending this infrastructure would be to create a new model class containing those arguments as properties

public class AddressModel
{
  public Person Person { get; set; }
  public Address Address { get; set; }
  public int Simple { get; set; }
}

And use that model in your controller action

public void AddAddress( AddressModel model );
like image 153
Pablo Cibraro Avatar answered Jul 21 '26 00:07

Pablo Cibraro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!