1

I have complex object for Get WebApi from uri,

At WebApi,

Public IHttpActionresult GetData([FromUri]ComplexModel model)
{
    //some code
}

public class ComplexModel
{
    public int Id {get; set;}
    public string name {get; set;}
}

At MVC,

Public void CallWebApi()
{
   using(HttpClient client = new HttpClient())
   {
      var uri = baseApi + "Contoller/GetData?Id=1&name=testname";
      var response = client.GetAsync(uri).Result;
   }
}  

Instead of passing complex object through query string, is there a better approach?

user472269
  • 367
  • 1
  • 4
  • 19

1 Answers1

1

If you require to use HTTP GET method, then you have no alternatives (apart from passing those parameters into some HTTP header, which, I believe, is not a good alternative).

To make simpler the creation of your endpoint URI you could create a static method that serializes your object into a query string.

Something like this should work (taken from this answer):

public string GetQueryString(object obj) {
    var properties = from p in obj.GetType().GetProperties()
                       where p.GetValue(obj, null) != null
                       select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(obj, null).ToString());

    return String.Join("&", properties.ToArray());
}

And use it in this way:

ComplexModel myModel = GetMyModel();
using(HttpClient client = new HttpClient())
{
   var uri = baseApi + "Contoller/GetData?" + GetQueryString(myModel);
   var response = await client.GetAsync(uri);
}

As an aside: please remember to never call asynchronous methods and then wait for their result in a synchronous way, this could lead to deadlocks.

Community
  • 1
  • 1
Federico Dipuma
  • 17,655
  • 4
  • 39
  • 56
  • It's good, but still model values are passed in querystring, i am looking for alternative approach instead of querystring. – user472269 May 27 '16 at 19:29
  • 1
    I assumed that your Web API method was `GET`. With `GET` you have no other options: you can't send a body for a `GET` request. If you want alternatives then you have to turn your method into `POST` or `PUT`. – Federico Dipuma May 27 '16 at 19:36