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

如何使用参数[FromBody]从C#发出HTTP修补程序请求,c#,api,rest,httprequest,patch,C#,Api,Rest,Httprequest,Patch,我正在创建一个web API服务,但在调用HTTP补丁请求时遇到了一些问题。虽然我知道如何创造它们。 如果您能帮助我,我将不胜感激,以下是我的代码: HTTP修补程序代码: [HttpPatch("{username}")] public async Task<ActionResult> Patch(string username, [FromBody] JsonPatchDocument<User> patchDocument)

我正在创建一个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();
            }

        }
[HttpPatch(“{username}”)]
公共异步任务修补程序(字符串用户名,[FromBody]JsonPatchDocument patchDocument)
{ 
//如果未传递任何信息,此API调用将返回BADDREQUEST
if(patchDocument==null)
返回请求();
var theUser=await connection.GetAUser(用户名);
var originalUser=await connection.GetAUser(用户名);
if(theUser==null)
返回NotFound();
//文档中指定的更改将应用于用户
patchDocument.ApplyTo(用户、模型状态);
//检查修补是否成功
bool isValid=TryValidateModel(用户);
如果(!isValid)
返回请求(ModelState);
其他的
{
bool check=wait connection.UpdateUser(originalUser,用户);
如果(检查!=真)
返回请求();
其他的
返回Ok();
}
}
与SQL数据库的关联(从前面的代码调用的方法):

public async Task UpdateUser(用户originalUser,用户patchedUser)
{
SqlCommand SqlCommand=新SqlCommand();
尝试
{
if(originalUser.password!=patchedUser.password)
{
//string命令=SQL命令
SqlParameter param1=新的SqlParameter();
param1.ParameterName=“@password”;
param1.Value=patchedUser.password;
SqlParameter param2=新的SqlParameter();
param2.ParameterName=“@username”;
param2.Value=patchedUser.username;
sqlCommand.CommandText=命令;
sqlCommand.Parameters.Add(param1);
sqlCommand.Parameters.Add(param2);
连接=新数据库连接服务(配置,sqlCommand);
等待连接。GetData();
}
其他的
返回true;
返回true;
}
捕获(异常错误)
{
返回false;
}
}
我已经在邮递员身上测试过了,效果非常好。问题是,我知道如何将来自Body的JsonPatchDocument传递给PostMan,但我不知道如何使用C#(我需要它从应用程序拨打电话)。 我试图寻找关于这个问题的答案,但我只找到了有关如何创建API的信息,而没有找到如何从C#调用API的信息。 就这些,如果您需要更多的信息,我会在看到您的请求后尽快提供,非常感谢您抽出时间,希望大家都过得愉快

编辑: 在深入研究这个问题之后,我找到了一种可行的方法,但它返回给我一个405状态代码(“不允许使用方法”): 这是我在C#应用程序中使用的代码

public异步任务PatchUser(UserModel用户\u Raw)
{
if(客户端==null)
初始化客户端();
尝试
{
//将UserModel转换为JsonPatchDocument
JsonPatchDocument body=新的JsonPatchDocument();
阀体。更换(e=e,用户_原始);
//将JSONPATCH文档转换为Json
var serializedJsonDocument=JsonConvert.SerializeObject(主体);
var stringUser=newstringcontent(serializedJsonDocument,unicodeincode.UTF8,“application/json”);
//
var request=newhttprequestmessage(newhttpmethod(“补丁”),“URL在这里”);
request.Content=stringUser;
//response存储Post结果,以便稍后确保它已成功
var response=wait client.sendaync(请求);
response.EnsureSuccessStatusCode();
字符串HttpResponse=wait response.Content.ReadAsStringAsync();
返回HttpResponse;
}
捕获(HttpRequestException错误)
{
返回null;
}
捕获(异常错误)
{
jsonResult=null;
返回jsonResult;
}
}

您是否在询问如何从C#应用程序发出修补程序请求?在这种情况下,为什么要显示所有不相关的服务器代码

要发出补丁请求,请实例化一个
HttpClient
,然后执行以下操作:

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

我展示它是因为我不知道它是否相关。我不能使用PatchAsync,我不知道为什么,但当我使用net.http时它不会出现。httpclient@JaimeSantos我扩展了答案。这有帮助吗?我更新了这个问题,试着这样做,总结一下,它给了我一个405的错误。我无法将JsonPatchDocument分配给HttpRequestMessage的内容,因此我做了几件事将其转换为StringContent。我可能做了错误的转换,如果你能检查出来,我将不胜感激。感谢您迄今为止的帮助,我感觉我几乎成功了(:@JaimeSantos我认为这与主体无关(要调试,请使用不接受任何主体参数的方法).405表示不允许使用该方法。如果您在IIS上托管,则可能必须编辑web.config:没关系,我使用了错误的URL,我再次尝试了该方法,效果很好,非常感谢您的帮助((:
        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;
            }
        }
    JsonPatchDocument<User> body = <...>;
    HttpResponseMessage response = await client.PatchAsync(requestUri, body);
    var request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri) {
        Content = body
    };
    var response = await client.SendAsync(request);