简体   繁体   English

如何使用参数 [FromBody] 从 C# 发出 HTTP 补丁请求

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

I am creating a web API Service but I am having some problems when it comes to calling HTTP Patch requests.我正在创建 web API 服务,但是在调用 HTTP 补丁请求时遇到了一些问题。 Though I know how to create them.虽然我知道如何创建它们。 If you could help me with this I would appreciate it, here is my code:如果您能帮助我,我将不胜感激,这是我的代码:

HTTP PATCH CODE: 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();
            }

        }

Corelation with SQL Database (Method called from the previous code):与 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;
            }
        }

I have tested it on PostMan, and it works perfectly.我在 PostMan 上测试过,效果很好。 The problem is that I know how to pass a JsonPatchDocument FromBody on PostMan, but I don't know how to do it using C# (I need this to make the call from an APP).问题是我知道如何在 PostMan 上传递 JsonPatchDocument FromBody,但我不知道如何使用 C#(我需要这个从 APP 进行调用)。 I have tried to look for answers regarding this issue, but I have only found information about how to create the API, not about how to call it from C#.我试图寻找有关此问题的答案,但我只找到有关如何创建 API 的信息,而不是有关如何从 C# 调用它的信息。 That is all, if you need any more information I will provide it as soon as I see your request, thank you all so much for your time, I hope everyone has good day.就是这样,如果您需要更多信息,我会在看到您的请求后立即提供,非常感谢大家的宝贵时间,希望每个人都有美好的一天。

EDIT: After diving deeper into this matter, I have found a way that could work, however It returns me a 405 status code ("Method not allowed"): This is the code that I use in my C# App编辑:在深入研究这个问题之后,我找到了一种可行的方法,但是它返回了一个 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;
            }
        }

Are you asking how to make a PATCH request from a C# application?您是否在问如何从 C# 应用程序发出 PATCH 请求? In that case, why are you showing all the irrelevant server code?在那种情况下,你为什么要显示所有不相关的服务器代码?

To make a PATCH request, you instantiate an HttpClient , and then do this:要发出 PATCH 请求,请实例化一个HttpClient ,然后执行以下操作:

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

If you're stuck with .NET Framework, you won't have PatchAsync , in which case you have to do something like this:如果您坚持使用 .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