Reputation: 113
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.
Upvotes: 1
Views: 8321
Reputation: 4776
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.
Upvotes: 0
Reputation: 4000
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
Upvotes: 2