简体   繁体   English

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

[英]PutAsync doesn't send request to web api, but fiddler works fine

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. 我一直试图弄清楚几个小时后出了什么问题,而我却找不到出错的地方。

Via the Mvc application the put method doesn't get hit, the request doesn't happen. 通过Mvc应用程序,put方法不会被命中,请求不会发生。 But when i test it in fiddler the PutMethod in the api works. 但是当我在小提琴手中测试它时,api中的PutMethod工作。

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"));

        }
    }

The above code is my service that should make the request to the api. 上面的代码是我的服务,应该向api发出请求。

Here is the web api IHttpActionResult method (the put method). 这是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);
    }

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

You have two choices. 你有两个选择。 Either make the method async Task and await inside it: 使方法成为async Task并在其中await

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"));

    }
}

Or use a synchronous API, such as exposed by WebClient . 或者使用同步API,例如WebClient公开的API。

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

相关问题 HttpClient PutAsync不向api发送参数 - HttpClient PutAsync doesn't send a parameter to api Putasync 400错误请求C#-Google APi Works - Putasync 400 Bad Request c# - google APi works 通过 PutAsync 请求发送“流” - Send a 'Stream' over a PutAsync request 对服务的PATCH请求在我的C#应用​​程序中不起作用,但在Fiddler中起作用 - PATCH request to the service doesn't work within my C# application, but works in Fiddler Web API .NET MVC - Http POST - Fiddler 请求发送字符串变量 - Web API .NET MVC - Http POST - Fiddler request send string variable 将JSON传递到Web.API可与Fiddler一起使用,但不适用于代码 - Passing JSON to Web.API works with Fiddler but not in code 通过Web请求进行PutAsync时缺少BsonDocument的值? - Values of BsonDocument missing when PutAsync over web request? Xamarin.Android应用程序不请求“WriteExternalStorage”(但代码适用于“ReadExternalStorage”) - Xamarin.Android app doesn't request “WriteExternalStorage” (but code works fine with “ReadExternalStorage”) Api 在提琴手中返回结果,但响应不是控制台中的结果 - Api returns result in fiddler but the response doesn't the result in console 使用PutAsync转发HttpPut请求 - Forwarding a HttpPut request with PutAsync
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM