代码之家  ›  专栏  ›  技术社区  ›  Conor Watson

HttpReportMessage的状态代码为200,但“Result”为空

  •  1
  • Conor Watson  · 技术社区  · 8 年前

    我目前正在开发一个与Web API集成的应用程序。我有一个异步函数,它发送一个 PUT 请求Web API以更新产品。

        public async Task<ResponseStatus> updateProduct(Item product)
        {
            string URL = client.BaseAddress + "/catalog/products/" + product.id;
            HttpResponseMessage response = await client.PutAsJsonAsync(URL, product).ConfigureAwait(false);
            var payload = response.Content.ReadAsStringAsync();
            ResponseStatus res = JsonConvert.DeserializeObject<ResponseStatus>(await payload.ConfigureAwait(false));
    
            return res;
        }
    

    在我用来测试应用程序的控制台应用程序中,该函数完全按照预期工作,我在 Result

    enter image description here

    然而,当我试图从ASP。Net应用程序中,我在 ,即使它的状态代码为200。我还可以看到我的更新没有在产品上生效,即使它在控制台应用程序中调用时肯定会更新。

    enter image description here

    GET

        public async Task<Product> getProductByID(int id)
        {
            Product product = null;
            string URL = client.BaseAddress + "/catalog/products/" + id;
            string additionalQuery = "include=images,variants";
            HttpResponseMessage response = await client.GetAsync(URL + "?" + additionalQuery).ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                var payload = response.Content.ReadAsStringAsync();
                product = JsonConvert.DeserializeObject<Product>(await payload.ConfigureAwait(false));
            }
            return product;
        }
    

    为什么在ASP。Net app即使 是否为空,并且实际上没有对产品进行更新?

    2 回复  |  直到 8 年前
        1
  •  1
  •   toadflakz    8 年前

    你需要 await 这个 payload Task ConfigureAwait(false) .

    通过使用 您不能保证保留ASP。当 Task Result 这是ASP的一个特点。NET运行时。

    它被称为 Best Practice tip for async/await by Microsoft

    对于ASP。NET应用程序,这包括任何使用HttpContext的代码。当前或生成ASP。净响应

        2
  •  1
  •   Conor Watson    8 年前

    对于任何遇到这个的人。我试图通过BigCommerce API更新产品,我的代码中有一个错误,其中 custom_url null

    enter image description here

    这显然在BigCommerce API服务器上产生了一个错误,但由于返回了成功代码200,因此无法正确处理,即使产品没有得到更新。这产生了我得到的空洞回应。

    推荐文章