通过HttpClient Post将数据发布到Web Api 2控制器

时间:2016-12-09 08:36:34

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

我的应用程序中有一个WebApi控制器

    [HttpPost]
    [Route("contracts/{exchangeGuid}/exchangeInfos")]
    public IHttpActionResult UpdateContractExchangeInfo(Guid exchangeGuid,ExchangeDestination destination, ExchangeStatus exchangeStatus, string response)
    {
       //some login here
    }

我需要使用HttpClient调用这个WebApi方法。 我试图使用表单数据进行PostAsync,但是在控制器上找不到这样的操作时出现错误

以下是我的请求示例

                using (var client = new HttpClient(clientHandler))
                {
                    client.BaseAddress = _baseAddress;
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

                    //Creating form content
                    var formContent = new FormUrlEncodedContent(new[]
                        {
                            new KeyValuePair<string, string>("destination", ((int)destination).ToString()),
                            new KeyValuePair<string, string>("exchangeStatus", ((int)exchangeStatus).ToString()),
                            new KeyValuePair<string, string>("response", ipResponse)
                        });

                    //Sending POST 
                    HttpResponseMessage response = await client.PostAsync(string.Format("api/contracts/{0}/exchangeInfos", contractGuid), formContent);

                    //Some more logic here
                 }

有没有办法创建post请求并传递此参数而不更改WebApi操作?

1 个答案:

答案 0 :(得分:0)

如果无法找到操作,我会在构建客户端之前先尝试访问端点,如果以调试模式启动web api项目为localhost,请尝试在浏览器中键入URL,看看是否可以点击端点使用您指定的相同参数。

相关问题