简体   繁体   English

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

[英]Posting data to Web Api 2 controller via HttpClient Post

I've got an WebApi controller in my application 我的应用程序中有一个WebApi控制器

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

I need to make a call to this WebApi method using HttpClient. 我需要使用HttpClient对此WebApi方法进行调用。 I've tried to make a PostAsync with form data but got an error that no such action was found on controller 我尝试使用表单数据进行PostAsync,但收到一个错误,即在控制器上未找到此类操作

Here is an example of my request 这是我的要求的一个例子

                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
                 }

Is there any way to create post request and pass this parameters without changing WebApi action? 有什么方法可以创建发布请求并传递此参数,而无需更改WebApi操作?

如果找不到该动作,则在构建客户端之前,我将先尝试访问该终结点,如果您以localhost作为调试模式启动Web api项目,请尝试在浏览器中键入URL,并查看是否可以使用以下命令访问该终结点与您指定的参数相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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