1

I have this AngularJS Http Call

$http({
       method: "POST",
       url: Helper.ApiUrl() + '/Api/Case/SendCase',
       data: { obecttype1, obj2, obj3},
                }).then(function mySuccess(response) {});

Ant this ASP.net Web Api method

[HttpPost]
[Route("Api/Path/SendCase")]
 public int SendCase(object application)
 {

 string applicantName = ((Newtonsoft.Json.Linq.JObject)application)["applicant"].ToString();

 obecttype1 obj = JsonConvert.DeserializeObject<obecttype1>(((Newtonsoft.Json.Linq.JObject)application)["obecttype1"].ToString());

   .........................
   return ID;
  }

This works pretty well, but I feel it is a bit dirty because I am parsing my objects in my method, so my question is

Is the are way to send multiple objects as params in a POST method, I would prefer to avoid modifying my model, avoid creating a class for this

So my Api Method would look like this

 public int SendCase(class1 obecttype1, class2 obj2, class3 obj3)
1
  • This isn't something you can do without creating a new class to hold objecttype1, obj2 and obj3. Commented Oct 6, 2017 at 17:35

3 Answers 3

2

"Is the are way to send multiple objects as params in a POST method, I would prefer to avoid modifying my model, avoid creating a class for this"

By design HTTP Post can only have one body and web api will try to cast the body to the parameter defined in the method signature. So sending multiple objects in the body and trying to match these against multiple params in the method signature will not work. For that you need to define a class which holds the other classes and match the body signature.

public class postDTO
{
    public class1 class1Data { get; set; }
    public class2 class2Data { get; set; }
    public class3 class3Data { get; set; }
}

//The api signature
public int SendCase(postDTO application)

If you still don't want to add the new class then I would use the JObject directly as the parameter as this

[HttpPost]
public int SendCase(JObject jsonData)
{
    dynamic json = jsonData;
    JObject class1DataJson = json.class1Data;
    JObject class2DataJson = json.class2Data;
    JObject class3DataJson = json.class3Data;

    var class1Data = class1DataJson.ToObject<class1>();
    var class2Data = class2DataJson.ToObject<class2>();
    var class3Data = class3DataJson.ToObject<class3>();
}
Sign up to request clarification or add additional context in comments.

2 Comments

HTTP Post can only have one body, but when you're posting multiple objects using Angular Http service or jQuery Ajax (Object must be key-value pairs), they're serialized as a JSON string (by default if you don't specify the content-type). Then when the JSON string is transferred to the server, ASP.NET Web API will try its best to read the values from the message body using Model Binding and Media-Type formatter. So putting multiple objects into 1 object is not necessary. In fact, the way I specify the object using { key1: value1, key2, value2 } is really a single object, anonymous object.
it is just a confirmation of my answer but I think it is correct
1

1. Define models for the parameters

public class ClassType1
{
    public int Num1 { get; set; }
    public string Str1 { get; set; }
}

public class ClassType2
{
    public double Test2 { get; set; }
}

2. Use the models as the parameters on the API controller method

// Sorry this example is setup on .Net Core 2.0 but I think the previous
// versions of Web Api would have similar/same behavior

[Route("api/[controller]")]
public class ValuesController : Controller
{
    [HttpPost]
    public void Post(ClassType1 ct1, ClassType2 ct2)
    {}
}

3. When posting, your objects inside the data {} have to have the keys that match the parameter name you defined on the Controller method

jQuery ajax

        $.ajax({
                method: 'post',
                url: 'http://localhost:53101/api/values',
                dataType: 'json',
                data: {
                    // It takes key value pairs
                    ct1: {
                        num1: 1,
                        str1: 'some random string'
                    },
                    ct2: {
                        test2: 0.34
                    }
                }
            });

To summarize, yes you can post multiple objects back to the server, as long as

  1. You define a key for each object and the key has to match the parameter name you define on the server method.
  2. The object structure has to match.

-- update --

Just as a proof, here is the screenshot:

enter image description here

3 Comments

It worked on my end. I created the sample and tested it first before posting. I just don't know if that's what you want from the beginning. Since you have your environment set up, i.e., Web API and Angular, why don't you try it and tell me if it's working or not.
I will try it when I move to aspnet core +1
I think ASP.NET Web Api works the same way. Give it a try if you have chance.
1

We have an app that uses DefaultHttpBatchHandler to accept multi-part POST requests. I believe it to be a bit clunky for many reasons but it is the built-in way to accept multiple objects on a single request in a structured fashion.

https://msdn.microsoft.com/en-us/library/system.web.http.batch.defaulthttpbatchhandler(v=vs.118).aspx

As for the script to create something, that I don't know about. Our callers that use this API are C# services that can create the multi-part requests using a simple client library we provide to help them do just that.

1 Comment

I will try it, sounds interesting

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.