如何解决在 C# 中将 JSON 数据发布到服务器时出现服务器错误
我有一个问题,我似乎无法解决问题。我正在尝试使用 httpClient 调用我的 web api,但收到 500 内部服务器错误。搜索了几个帖子,但找不到确切的问题。我知道它是 JSON 格式,但不确定缺少什么。以下是我的客户端功能:
[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(),"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();
}
}
这是我的 InputJson:
"{\"PnsHandle\":\"<value>\",\"PnsType\":\"<value>\",\"Template\":\"{\"data\":{\"title\":\"$(title)\",\"message\":\"$(message)\"}}\",\"TagList\":\"<value>\",\"InstallationId\":\"<value>\",\"AzureHubServiceName\":\"<value>\",\"AzureHubName\":\"<value>\",\"AzureHubListenAccessKeyName\":\"<value>\",\"AzureHubListenAccessKeyValue\":\"<value>\"}"
当我使用必需的输入和高于 InputJson 值执行 myCallStoredProc 时,出现以下错误:
解析值后遇到意外字符:d。路径“模板”,第 1 行,位置 110。
我的 web api 如下所示:
[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);
}
}
我尝试使用在线 json 格式化程序格式化输入 json,在删除转义符 '' 后,json 结果很好。
我搜索了多个具有相同问题 here 和 here 的帖子,但他们正在讨论如何发送帖子数据,例如使用 httpwebrequest 或使用我已经在做的 httpClient。
对我在这里可能做错的事情有任何评论吗?在我看来是 json 格式问题,但不确定。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。