C# 如何使用c中的web API补丁#
我需要使用C代码中的web API补丁方法。我的控制器如下:C# 如何使用c中的web API补丁#,c#,asp.net,httpclient,asp.net-core-webapi,patch,C#,Asp.net,Httpclient,Asp.net Core Webapi,Patch,我需要使用C代码中的web API补丁方法。我的控制器如下: [HttpPatch("updateMessageTemplate/{templateId}")] public IActionResult UpdateMessageTemplate([FromHeader] int clientId, int templateId,[FromBody] string template) { try { notificationService.UpdateMessag
[HttpPatch("updateMessageTemplate/{templateId}")]
public IActionResult UpdateMessageTemplate([FromHeader] int clientId, int templateId,[FromBody] string template)
{
try
{
notificationService.UpdateMessageTemplate(clientId,templateId,template);
return Accepted();
}
catch
{
return StatusCode(500);
}
}
我刚刚尝试了如下C#代码来使用我的API补丁方法
public string UpdateMessageTemplate(string token, int clientId, int templateID, string template)
{
try
{
string serviceUrl = string.Format("{0}/notification/updateMessageTemplate/{1}", ConfigurationManager.AppSettings["APIURL"], templateID);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("clientId", clientId.ToString());
client.DefaultRequestHeaders.Add("Authorization", string.Format("bearer {0}", token));
var response = client.PatchAsync(serviceUrl).Result;
return response;
}
catch (Exception ex)
{
NameValueCollection logParams = new NameValueCollection();
Logger.LogErrorEvent(ex, logParams);
throw;
}
}
但上述消费方法是错误的。你能告诉我正确的食用方法吗 您的代码有两个问题:
未添加templateIDstring.Format(“{0}/notification/updateMessageTemplate”,ConfigurationManager.AppSettings[“APIURL”],templateID)
- 您没有将
作为正文传递给Requirest模板
public string UpdateMessageTemplate(string token, int clientId, int templateID, string template) { try { string serviceUrl =$"{ConfigurationManager.AppSettings["APIURL"]}/notification/updateMessageTemplate/{templateID}"; HttpClient client = new HttpClient(); StringContent content = new StringContent(template); client.DefaultRequestHeaders.Add("clientId", clientId.ToString()); client.DefaultRequestHeaders.Add("Authorization", string.Format("bearer {0}", token)); var response = client.PatchAsync(serviceUrl, content).Result; return response; } catch (Exception ex) { NameValueCollection logParams = new NameValueCollection(); Logger.LogErrorEvent(ex, logParams); throw; } }
StringContent
版本
上面修改的代码应该可以解决您的问题。另一个建议是使用aysnc/await链,而不是在异步调用上使用
.Result
,这可能会在代码中造成死锁。您的API需要{templateId}
,但形成的url不包含该内容。另外,要传递template
,您需要从客户端以StringContent
的形式传递正文。@user1672994抱歉,我错过了{templateId}
(更新了代码)。您能给我一个示例代码吗?如何从客户端将正文作为字符串传递给我<代码>错误CS1061“HttpClient”不包含“PatchAsync”的定义,并且找不到可访问的扩展方法“PatchAsync”接受类型为“HttpClient”的第一个参数(是否缺少using指令或程序集引用?此错误在我之前的代码中显示为第一个参数HttpClient
?有关PatchAsync
方法的定义,请参见。另外,我刚刚修复了我发布的代码中的一个小错误。如何传递apirl
?我将代码更改为string serviceUrl=string.Format(“{0}/notification/updateMessageTemplate/{1}”,ConfigurationManager.AppSettings[“LtApiUrl”],templateID)
但仍然有错误(不包含“PatchAsync”的定义,并且没有可访问的扩展方法“PatchAsync”接受类型为“HttpClient”的第一个参数
),您是否在代码中添加了所需的名称空间,即System.Net.Http
和System.Net
?我正在使用使用System.Net.Http代码>请查看此图像我的代码不建议PatchAsync