简体   繁体   中英

How to call [HttpPost] method of web api in c#

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM