I have a problem that I can't seem to wrap my head around. I am trying to call my web api using httpClient but getting a 500 Internal server error. Searched several posts but couldn't find the exact issue. I know it is JSON formatting but not sure what's missing. Below is my client function:
[Microsoft.SqlServer.Server.SqlProcedure(Name = "myCallStoredProc")]
public static void myCallStoredProc(SqlString BaseApiUrl, SqlString ApiName, SqlString ApiKey, SqlString InputJson, out int RtnCd, out string RtnMsg)
{
try
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(BaseApiUrl.ToString());
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Add("API_KEY", ApiKey.ToString());
//var content = new StringContent(null, Encoding.UTF8, "application/json");
var content = new StringContent(InputJson.ToString(), Encoding.UTF8, "application/json");
var response = httpClient.PostAsync(ApiName.ToString(), content).Result;
RtnCd = response.IsSuccessStatusCode == true ? 0 : -1;
RtnMsg = RtnCd == -1 ? response.Content.ReadAsStringAsync().Result : "";
return;
}
catch (Exception ex)
{
RtnCd = -1;
RtnMsg = ex.ToString();
}
}
This is my InputJson:
"{"PnsHandle":"<value>","PnsType":"<value>","Template":"{"data":{"title":"$(title)","message":"$(message)"}}","TagList":"<value>","InstallationId":"<value>","AzureHubServiceName":"<value>","AzureHubName":"<value>","AzureHubListenAccessKeyName":"<value>","AzureHubListenAccessKeyValue":"<value>"}"
When I execute myCallStoredProc with required input and above InputJson value, I get following error:
After parsing a value an unexpected character was encountered: d. Path 'Template', line 1, position 110.
My web api looks like below:
[HttpPost]
public async Task<HttpResponseMessage> myAPI(HttpRequestMessage request)
{
try
{
string input = await request.Content.ReadAsStringAsync();
JObject inputValues = JObject.Parse(input);
// Do Something with inputValues
return Request.CreateResponse(HttpStatusCode.OK, result);
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
I tried to format the input json using online json formatters and after removing the escape '' the json turned out fine.
I searched multiple posts with same issues here and here but they are talking about how to send the post data like using httpwebrequest or using httpClient which I am already doing.
Any comments on what I might be doing wrong here? It seems to me the json formatting issue but not sure.