简体   繁体   中英

Posting data to Web Api 2 controller via HttpClient Post

I've got an WebApi controller in my application

    [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. I've tried to make a PostAsync with form data but got an error that no such action was found on controller

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?

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

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