簡體   English   中英

如何使用參數 [FromBody] 從 C# 發出 HTTP 補丁請求

[英]How to make an HTTP Patch request from C# with a parameter [FromBody]

我正在創建 web API 服務,但是在調用 HTTP 補丁請求時遇到了一些問題。 雖然我知道如何創建它們。 如果您能幫助我,我將不勝感激,這是我的代碼:

HTTP 補丁代碼:

[HttpPatch("{username}")]
        public async Task<ActionResult> Patch(string username, [FromBody] JsonPatchDocument<User> patchDocument)
        { 
            //If no info has been passed, this API call will return badrequest
            if (patchDocument == null)
                return BadRequest();

            var theUser = await connection.GetAUser(username);
            var originalUser = await connection.GetAUser(username);

            if (theUser == null)
                return NotFound();

            //Changes specified in the patchdocument are applied to the user
            patchDocument.ApplyTo(theUser, ModelState);
            //check if the patching has been successful or not
            bool isValid = TryValidateModel(theUser);

            if (!isValid)
                return BadRequest(ModelState);
            else
            {
                bool check = await connection.UpdateUser(originalUser, theUser);
                if (check != true)
                    return BadRequest();
                else
                    return Ok();
            }

        }

與 SQL 數據庫的關聯(從前面的代碼調用的方法):

        public async Task<bool> UpdateUser(User originalUser, User patchedUser)
        {
            SqlCommand sqlCommand = new SqlCommand();
            try
            {
                if (originalUser.password != patchedUser.password)
                {
                    //string command = SQL COMMAND
                    SqlParameter param1 = new SqlParameter();
                    param1.ParameterName = "@password";
                    param1.Value = patchedUser.password;
                    SqlParameter param2 = new SqlParameter();
                    param2.ParameterName = "@username";
                    param2.Value = patchedUser.username;

                    sqlCommand.CommandText = command;
                    sqlCommand.Parameters.Add(param1);
                    sqlCommand.Parameters.Add(param2);

                    connection = new DataBaseConnectionService(configuration, sqlCommand);
                    await connection.GetData();
                }
                else
                    return true;
                return true;
            }
            catch (Exception error)
            {
                return false;
            }
        }

我在 PostMan 上測試過,效果很好。 問題是我知道如何在 PostMan 上傳遞 JsonPatchDocument FromBody,但我不知道如何使用 C#(我需要這個從 APP 進行調用)。 我試圖尋找有關此問題的答案,但我只找到有關如何創建 API 的信息,而不是有關如何從 C# 調用它的信息。 就是這樣,如果您需要更多信息,我會在看到您的請求后立即提供,非常感謝大家的寶貴時間,希望每個人都有美好的一天。

編輯:在深入研究這個問題之后,我找到了一種可行的方法,但是它返回了一個 405 狀態代碼(“方法不允許”):這是我在 C# 應用程序中使用的代碼

        public async Task<string> PatchUser(UserModel User_Raw)
        {
            if (client == null)
                InitializeClient();

            try
            {
                //converts the UserModel to JsonPatchDocument<UserModel>
                JsonPatchDocument<UserModel> body = new JsonPatchDocument<UserModel>();
                body.Replace(e = e, User_Raw);

                //Converts the JsonPatchDocument<UserModel> to Json
                var serializedJsonDocument = JsonConvert.SerializeObject(body);
                var stringUser = new StringContent(serializedJsonDocument, UnicodeEncoding.UTF8, "application/json");

                //
                var request = new HttpRequestMessage(new HttpMethod("PATCH"), "Here goes the URL");
                request.Content = stringUser;

                //response stores the Post result to later ensure that it has been successful
                var response = await client.SendAsync(request);
                response.EnsureSuccessStatusCode();

                string HttpResponse = await response.Content.ReadAsStringAsync();
                return HttpResponse;
            }
            catch (HttpRequestException error)
            {
                return null;
            }
            catch (Exception error)
            {
                jsonResult = null;
                return jsonResult;
            }
        }

您是否在問如何從 C# 應用程序發出 PATCH 請求? 在那種情況下,你為什么要顯示所有不相關的服務器代碼?

要發出 PATCH 請求,請實例化一個HttpClient ,然后執行以下操作:

    JsonPatchDocument<User> body = <...>;
    HttpResponseMessage response = await client.PatchAsync(requestUri, body);

如果您堅持使用 .NET 框架,您將沒有PatchAsync ,在這種情況下您必須執行以下操作:

    var request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri) {
        Content = body
    };
    var response = await client.SendAsync(request);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM