PutAsync不会向web api发送请求,但fiddler工作正常

时间:2016-03-23 08:32:07

标签: c# asp.net async-await asp.net-web-api2 dotnet-httpclient

我一直试图弄清楚几个小时后出了什么问题,但我无法找到问题所在。

通过Mvc应用程序,put方法没有被击中,请求也没有发生。但是当我在小提琴手中测试它时,api中的PutMethod工作。

希望有人能为我解决问题。

欢迎提供更好结构或一些好文档的指示。

    public void UpdateWerknemerCompetentieDetail(int wnID, int WNC, CompetentieWerknemerDetail detail)
    {
        using (HttpClient client = new HttpClient())
        {
            string token = (string)HttpContext.Current.Session["token"];
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            var wn = GetWerknemerById(wnID);
            //var wnc = wn.CompetentiesWerknemer.Select(c => c).Where(c => c.ID == WNC).FirstOrDefault();
            detail.CompetentieWerknemerID = WNC;
            //wnc.CompetentieWerknemerDetail = detail;
            var url = String.Format(URL + "PutDetails?id=" + WNC);
             var json = JsonConvert.SerializeObject(detail, new JsonSerializerSettings()
             {
                 ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
             });         
            var response =  client.PutAsync(url, new StringContent(json, Encoding.UTF8, "application/json"));

        }
    }

以上代码是我的服务,应该向api发出请求。

这是web api IHttpActionResult方法(put方法)。

    [Route("PutDetails")]
    [HttpPut]
    public IHttpActionResult PutWerknemerCompetentieDetails(int id, [FromBody]CompetentieWerknemerDetail cwn)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != cwn.CompetentieWerknemerID)
        {
            return BadRequest();
        }

        //_db.Entry(cwn).State = EntityState.Modified;

        try
        {
            _db.CompetentieWerknemerDetail.Add(cwn);
            _db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!WerknemerExist(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

1 个答案:

答案 0 :(得分:4)

HttpClient.PutAsync是一个异步API,它返回一个Task<HttpResponseMessage>,表示将来需要await完成的操作。您将HttpClient包装在using语句中,这意味着在您触发异步PUT之后,您正在处理客户端,这会导致请求和对象处置的竞争条件,这可能是你没有看到请求的原因。

你有两个选择。在其中创建方法async Taskawait

public async Task UpdateWerknemerCompetentieDetailAsync(
        int wnID, int WNC, CompetentieWerknemerDetail detail)
{
    using (HttpClient client = new HttpClient())
    {
        string token = (string)HttpContext.Current.Session["token"];
        client.DefaultRequestHeaders.Authorization = 
                new AuthenticationHeaderValue("Bearer", token);
        var wn = GetWerknemerById(wnID);
        //var wnc = wn.CompetentiesWerknemer.Select(c => c)
        //                                  .Where(c => c.ID == WNC)
        //                                  .FirstOrDefault();

        detail.CompetentieWerknemerID = WNC;
        //wnc.CompetentieWerknemerDetail = detail;
        var url = String.Format(URL + "PutDetails?id=" + WNC);
        var json = JsonConvert.SerializeObject(detail, new JsonSerializerSettings()
        {
             ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        });         
        var response = await client.PutAsync(
            url, new StringContent(json, Encoding.UTF8, "application/json"));

    }
}

或使用同步API,例如WebClient公开。