json C# WebForms中更新一个参数的PUT请求

bvk5enib  于 2023-01-06  发布在  C#
关注(0)|答案(1)|浏览(106)

我正在开发一个网络应用程序,将通过WooCommerce REST API管理WooCommerce订单。
我尝试在用户单击按钮后更新订单状态。
当我运行应用程序时,点击按钮,我得到一个200 - OK状态,但顺序保持不变,没有更新完成。
以下是文档中的cURL示例:

curl -X PUT https://example.com/wp-json/wc/v3/orders/727 \
-u consumer_key:consumer_secret \
-H "Content-Type: application/json" \
-d '{
"status": "completed"
}'

在Postman上,我执行了查询,它运行得很好,在主体(raw-JSON)上添加了以下代码,通过一个PUT请求:

{
    "status": "cancelled"
}

现在,这是我的C#代码,关于按钮的onClick操作:

#region Request

            string nuevoEstado = "trash";

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlRequestInicial);
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method = "PUT";
            httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(apiUsr + ":" + apiPwd));
            httpWebRequest.UseDefaultCredentials = true;
            httpWebRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                var serializaer = new JavaScriptSerializer();
                var elJeison = serializaer.Serialize(new
                {
                    status = nuevoEstado
                });

                streamWriter.Write(elJeison);
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            string returnString = httpResponse.StatusCode.ToString();

            ltErr.Text = returnString;
#endregion

returnString显示“OK”,但没有进行更新。
任何帮助都非常感谢

bxjv4tth

bxjv4tth1#

我用另一种方法解决了这个问题。我把它贴在这里,以防有人遇到我遇到的同样的问题:
我将方法更改为异步void

using System.Net.Http;
using System.Net.Http.Headers;

protected async void btnCompletarPedidoApiAxnAsync (object sender, EventArgs e)
{
    ...
}

我设置了一个using块,改变了HttpClient()的方法;

using (var httpClient = new HttpClient())
            {
                using (var request = new HttpRequestMessage(new HttpMethod("PUT"), laUrl))
                {
                    var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes(apiUsr + ":" + apiPwd));
                    request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");

                    request.Content = new StringContent("{\n  \"status\": \"completed\"\n}");
                    request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                    var response = await httpClient.SendAsync(request);
                    
                    string responseBody = await response.Content.ReadAsStringAsync();
                }
            }

相关问题