HttpClient PostAsync返回.NET Core 2.0中找不到错误404

时间:2018-07-13 18:59:29

标签: c# httpclient asp.net-core-2.0

我正在尝试使用httpclient调用webapi。但这不是识别方法,总是抛出404错误。

我的api Action方法是这样的。

[Route("AddEmployee")]
    [HttpPost]
    public async Task<IActionResult> PostTEmployee([FromBody]Employee emp)
    { // doing something here}

调用方法如下所示

using (var httpClient = new HttpClient())
                {i

                    String BaseUrl = "http://ip:port/";
                    httpClient.BaseAddress = new Uri(BaseUrl);
                    AuthenticationHeaderValue parsedAuthToken = null;
                    bool authParsed = AuthenticationHeaderValue.TryParse(authToken, out parsedAuthToken);
                    if (authParsed)
                    {
                        httpClient.DefaultRequestHeaders.Authorization = parsedAuthToken;
                    }
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    string serialisedData = JsonConvert.SerializeObject(emp);
                    HttpContent content = new StringContent(serialisedData, Encoding.UTF8, "application/json");
                    HttpResponseMessage response = null;
                    response = await httpClient.PostAsync("AddEmployee", content);
                    if (response.IsSuccessStatusCode)
                    {
                    }

                }

从2天开始,我就一直坚持这个问题。不知道这是什么错误?请帮助我。

1 个答案:

答案 0 :(得分:0)

完全是一个疯狂的猜测,但是您的端点/api/AddEmployee不是/AddEmployee吗?

尝试更改

response = await httpClient.PostAsync("AddEmployee", content);

收件人

response = await httpClient.PostAsync("api/AddEmployee", content);