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.

4

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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''
There is a 100 ways how to convert instance of a class to NameValueCollection, I have added one of them to my answer.

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.