Can some please help me to know how to pass multiple objects from a C# console app to Web API controller as shown below?
using (var httpClient = new System.N
Create one complex object to combine Content and Config in it as others mentioned, use dynamic and just do a .ToObject(); as:
[HttpPost]
public void StartProcessiong([FromBody] dynamic obj)
{
var complexObj= obj.ToObject<ComplexObj>();
var content = complexObj.Content;
var config = complexObj.Config;
}
Here's another pattern that may be useful to you. It's for a Get but the same principle and code applies for a Post/Put but in reverse. It essentially works on the principle of converting objects down to this ObjectWrapper class which persists the Type's name to the other side:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace WebAPI
{
public class ObjectWrapper
{
#region Public Properties
public string RecordJson { get; set; }
public string TypeFullName { get; set; }
#endregion
#region Constructors
public ObjectWrapper() : this(null, null)
{
}
public ObjectWrapper(object objectForWrapping) : this(objectForWrapping, null)
{
}
public ObjectWrapper(object objectForWrapping, string typeFullName)
{
if (typeFullName == null && objectForWrapping != null)
{
TypeFullName = objectForWrapping.GetType().FullName;
}
else
{
TypeFullName = typeFullName;
}
RecordJson = JsonConvert.SerializeObject(objectForWrapping);
}
#endregion
#region Public Methods
public object ToObject()
{
var type = Type.GetType(TypeFullName);
return JsonConvert.DeserializeObject(RecordJson, type);
}
#endregion
#region Public Static Methods
public static List<ObjectWrapper> WrapObjects(List<object> records)
{
var retVal = new List<ObjectWrapper>();
records.ForEach
(item =>
{
retVal.Add
(
new ObjectWrapper(item)
);
}
);
return retVal;
}
public static List<object> UnwrapObjects(IEnumerable<ObjectWrapper> objectWrappers)
{
var retVal = new List<object>();
foreach(var item in objectWrappers)
{
retVal.Add
(
item.ToObject()
);
}
return retVal;
}
#endregion
}
}
In the REST code:
[HttpGet]
public IEnumerable<ObjectWrapper> Get()
{
var records = new List<object>();
records.Add(new TestRecord1());
records.Add(new TestRecord2());
var wrappedObjects = ObjectWrapper.WrapObjects(records);
return wrappedObjects;
}
This is the code on the client side (UWP) using a REST client library. The client library just uses the Newtonsoft Json serialization library - nothing fancy.
private static async Task<List<object>> Getobjects()
{
var result = await REST.Get<List<ObjectWrapper>>("http://localhost:50623/api/values");
var wrappedObjects = (IEnumerable<ObjectWrapper>) result.Data;
var unwrappedObjects = ObjectWrapper.UnwrapObjects(wrappedObjects);
return unwrappedObjects;
}
Basically you can send complex object without doing any extra fancy thing. Or without making changes to Web-Api. I mean why would we have to make changes to Web-Api, while the fault is in our code that's calling the Web-Api.
All you have to do use NewtonSoft's Json library as following.
string jsonObjectA = JsonConvert.SerializeObject(objectA);
string jsonObjectB = JsonConvert.SerializeObject(objectB);
string jSoNToPost = string.Format("\"content\": {0},\"config\":\"{1}\"",jsonObjectA , jsonObjectB );
//wrap it around in object container notation
jSoNToPost = string.Concat("{", jSoNToPost , "}");
//convert it to JSON acceptible content
HttpContent content = new StringContent(jSoNToPost , Encoding.UTF8, "application/json");
var response = httpClient.PutAsync("api/process/StartProcessiong", content);
Create a Composite object
public class CollectiveObject<X, Y>
{
public X FirstObj;
public Y SecondObj;
}
initialize a composite object with any two objects which you willing to send.
CollectiveObject<myobject1, myobject2> collectiveobj =
new CollectiveObject<myobject1, myobject2>();
collectiveobj.FirstObj = myobj1;
collectiveobj.SecondObj = myobj2;
Do serialization
var req = JSONHelper.JsonSerializer`<CollectiveObject<myobject1, `myobject2>>(collectiveobj);`
`
your API must be like
[Route("Add")]
public List<APIAvailibilityDetails> Add([FromBody]CollectiveObject<myobject1, myobject2> collectiveobj)
{ //to do}
In the current version of Web API, the usage of multiple complex objects (like your Content
and Config
complex objects) within the Web API method signature is not allowed. I'm betting good money that config
(your second parameter) is always coming back as NULL. This is because only one complex object can be parsed from the body for one request. For performance reasons, the Web API request body is only allowed to be accessed and parsed once. So after the scan and parsing occurs of the request body for the "content" parameter, all subsequent body parses will end in "NULL". So basically:
[FromBody]
.[FromUri]
.Below is a useful extract from Mike Stall's excellent blog article (oldie but goldie!). You'll want to pay attention to item 4:
Here are the basic rules to determine whether a parameter is read with model binding or a formatter:
- If the parameter has no attribute on it, then the decision is made purely on the parameter's .NET type. "Simple types" use model binding. Complex types use the formatters. A "simple type" includes: primitives,
TimeSpan
,DateTime
,Guid
,Decimal
,String
, or something with aTypeConverter
that converts from strings.- You can use a
[FromBody]
attribute to specify that a parameter should be from the body.- You can use a
[ModelBinder]
attribute on the parameter or the parameter's type to specify that a parameter should be model bound. This attribute also lets you configure the model binder.[FromUri]
is a derived instance of[ModelBinder]
that specifically configures a model binder to only look in the URI.- The body can only be read once. So if you have 2 complex types in the signature, at least one of them must have a
[ModelBinder]
attribute on it.It was a key design goal for these rules to be static and predictable.
A key difference between MVC and Web API is that MVC buffers the content (e.g. request body). This means that MVC's parameter binding can repeatedly search through the body to look for pieces of the parameters. Whereas in Web API, the request body (an
HttpContent
) may be a read-only, infinite, non-buffered, non-rewindable stream.
You can read the rest of this incredibly useful article on your own so, to cut a long story short, what you're trying to do is not currently possible in that way (meaning, you have to get creative). What follows is not a solution, but a workaround and only one possibility; there are other ways.
(Disclaimer: I've not used it myself, I'm just aware of the theory!)
One possible "solution" is to use the JObject object. This objects provides a concrete type specifically designed for working with JSON.
You simply need to adjust the signature to accept just one complex object from the body, the JObject
, let's call it stuff
. Then, you manually need to parse properties of the JSON object and use generics to hydrate the concrete types.
For example, below is a quick'n'dirty example to give you an idea:
public void StartProcessiong([FromBody]JObject stuff)
{
// Extract your concrete objects from the json object.
var content = stuff["content"].ToObject<Content>();
var config = stuff["config"].ToObject<Config>();
. . . // Now do your thing!
}
I did say there are other ways, for example you can simply wrap your two objects in a super-object of your own creation and pass that to your action method. Or you can simply eliminate the need for two complex parameters in the request body by supplying one of them in the URI. Or ... well, you get the point.
Let me just reiterate I've not tried any of this myself, although it should all work in theory.