本文介绍了PutAsync不会将请求发送到Web api,但是提琴手可以正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个小时以来,我一直在试图找出问题所在,而我只是找不到问题所在.

I have been trying to figure out what is going wrong for a few hours now and i just can't find what is going wrong.

通过Mvc应用程序,put方法不会被命中,请求不会发生.但是,当我在提琴手中对其进行测试时,api中的PutMethod可以正常工作.

Via the Mvc application the put method doesn't get hit, the request doesn't happen. But when i test it in fiddler the PutMethod in the api works.

希望有人可以帮我清理一下.

Hopefully someone can clear things up for me.

也欢迎使用指针以提供更好的结构或一些好的文档.

Also pointers for a better structure or some good documentation are welcome .

    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发出请求.

The above code is my service that should make the request to the api.

这是Web api IHttpActionResult方法(put方法).

Here is the web api IHttpActionResult method (the put method).

    [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);
    }

推荐答案

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

HttpClient.PutAsync is an asynchronous API, it returns a Task<HttpResponseMessage> which represents an operation which will complete in the future, which you need to await. You're wrapping your HttpClient inside a using statement, which means that right after you trigger the asynchronous PUT, you're disposing the client which causes a race condition with the request and the disposal of your object, and is probably the reason you're not seeing the request fire.

您有两种选择.可以在其中使用方法 async Task await :

You have two choices. Either make the method async Task and await inside it:

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 .

Or use a synchronous API, such as exposed by WebClient.

这篇关于PutAsync不会将请求发送到Web api,但是提琴手可以正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 22:17
查看更多