我正在创建一个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 Framework,则不必这样做PatchAsync
,在这种情况下,你必须执行以下操作:
var request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri) {
Content = body
};
var response = await client.SendAsync(request);
我显示它是因为我不知道它是否有意义。我不能使用PatchAsync,我不知道为什么,但是当我使用net.http.httpclient时它不会出现
@JaimeSantos我扩展了答案。有帮助吗?
我更新了尝试此问题的方法,对其进行了总结,它给了我405错误。我无法将JsonPatchDocument分配给HttpRequestMessage的内容,因此我做了几件事将其转换为StringContent。我可能是错误地进行了转换,如果您可以检查出来,我将不胜感激。到目前为止,谢谢您的帮助,我觉得我快到了(:
@JaimeSantos我认为这与主体没有任何关系(要进行调试,请使用不带有任何主体参数的方法)。405表示不允许该方法。如果您在IIS上托管,则可能必须编辑web.config:stackoverflow.com/questions/19162825/…
没关系,我使用了错误的URL,我再次尝试了它,效果很好,非常感谢您的帮助((((