Reputation: 483
I need to consume my web API PATCH method from C# code. My controller as follows,
[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);
}
}
I just tried C# code as follows to consume my API PATCH method.
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;
}
}
But above consume method is wrong. can you please tell me what is the correct way to consume it?
Upvotes: 0
Views: 846
Reputation: 10839
Your code has two issues :
string.Format("{0}/notification/updateMessageTemplate", ConfigurationManager.AppSettings["APIURL"], templateID)
is not adding the templateId.
You are not passing template
as body to requrest
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;
}
}
If your code is expecting the encoding and media type in body content then use this version of
StringContent
.
The above modified code should fix your issue. Another suggestion - Use aysnc/await chain instead of using .Result
on async call which can create the deadlock in your code.
Upvotes: 1