【问题标题】:How to call [HttpPost] method of web api in c#c#中如何调用web api的[HttpPost]方法
【发布时间】:2015-02-18 02:06:06
【问题描述】:

我有一个方法,我需要调用它。

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

我需要通过 httpclient 或 HttpWebRequest 调用此方法,我的意思是任何方式。

【问题讨论】:

标签: c# asp.net-web-api http-post


【解决方案1】:

使用HttpClient 你可以这样做:

        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

【讨论】:

    【解决方案2】:

    我建议您使用WebClient。示例如下:

            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);
            }
    

    添加 要将您的数据转换为 nameValue 集合,您可以使用下一个:

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

    然后在 POST 请求中使用formFields

    【讨论】:

    • 在数据的地方,它需要 NameValueCollection。当我直接使用我的对象时,它会给出错误:-'Argument 3: cannot convert from 'SomeModel' to 'System.Collections.Specialized.NameValueCollection''
    • 有 100 种方法可以将类的实例转换为 NameValueCollection,我已将其中一种添加到我的答案中。
    猜你喜欢
    • 2014-10-13
    • 2012-07-09
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多