1

I have one method and i need to call it.

    [HttpPost]
    public List<MyClass> GetPanels(SomeModel filter)
    {
    ...
    //doing something with filter...
    ...
    return new List<MyClass>();
    }

I need to call this method by httpclient or HttpWebRequest , i mean any way.

Ashish Kumar
  • 113
  • 2
  • 4
  • 11

2 Answers2

2

Using the HttpClient you can do like this:

        var client = new HttpClient();
        var content = new StringContent(JsonConvert.SerializeObject(new SomeModel {Message = "Ping"}));
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var response = await client.PostAsync("http://localhost/yourhost/api/yourcontroller", content);

        var value = await response.Content.ReadAsStringAsync();

        var data = JsonConvert.DeserializeObject<MyClass[]>(value);

        // do stuff
peco
  • 3,890
  • 1
  • 20
  • 27
0

I would recommend you to use WebClient. Here is the example:

        using (var wb = new WebClient())
        {
            var uri = new Uri("http://yourhost/api/GetPanels");
            // Your headers, off course if you need it
            wb.Headers.Add(HttpRequestHeader.Cookie, "whatEver=5");
            // data - data you need to pass in POST request
            var response = wb.UploadValues(uri, "POST", data);
        }

ADDED To convert your data to nameValue collection you can use next:

NameValueCollection formFields = new NameValueCollection();

data.GetType().GetProperties()
    .ToList()
    .ForEach(pi => formFields.Add(pi.Name, pi.GetValue(data, null).ToString()));

Then just use the formFields in POST request.

Maris
  • 4,608
  • 6
  • 39
  • 68
  • In the place of data it requires NameValueCollection. When i use my object directly it gives error:- 'Argument 3: cannot convert from 'SomeModel' to 'System.Collections.Specialized.NameValueCollection'' – Ashish Kumar Dec 19 '14 at 08:55
  • There is a 100 ways how to convert instance of a class to NameValueCollection, I have added one of them to my answer. – Maris Dec 19 '14 at 14:34