如何从 c# 使用 Web API 补丁



我需要从C#代码中使用我的Web API PATCH方法。我的控制器如下,

[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 PATCH 方法。

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;
}
}

但上面的消费方法是错误的。 你能告诉我正确的消费方式是什么吗?

您的代码有两个问题:

  • string.Format("{0}/notification/updateMessageTemplate", ConfigurationManager.AppSettings["APIURL"], templateID)不会添加模板 ID。

  • 你不是把template作为身体来传递要求

    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,这可能会在代码中造成死锁。

最新更新