我有一种我不明白的情况。
我有一个c#类库应用程序,当我在VS2017中以调试模式逐步执行它时,它可以正常工作。
当我在“调试”模式下编译它并从控制台应用程序调用它时,它在调用https API端点时失败并且不报告任何错误。
这就是我调用“CreateOrder”的方式:
// send the order to DNAGenotek
DNAGenotek.Model.Order.CreateResponse.CreateOrderResponse orderResponse = await DNAGenotek.Orders.CreateOrder(DNAGenotekAPIKey, DNAGenotekOrder);
这就是我调用“CallAPIString”函数的方式:
public static async Task<Model.Order.CreateResponse.CreateOrderResponse> CreateOrder(string APIKey, Model.Order.Create.Order order)
{
// convert the object to a string
string orderAsString = JsonConvert.SerializeObject(order);
// create the order
string result = await Helpers.CallAPIString(APIKey, "https://sofia-stage.dnagenotek.com/api/v2/orders", "POST", orderAsString);
DNAGenotek.Model.Order.CreateResponse.CreateOrderResponse orderResponse = JsonConvert.DeserializeObject<Model.Order.CreateResponse.CreateOrderResponse>(result);
return orderResponse;
}
我已经附加到正在运行的控制台.exe并逐步执行,并且在执行POST时它在此行上失败
WebResponse httpResponseGETDELETE = await httpWebRequest.GetResponseAsync();
在以下代码中:
public static async Task<string> CallAPIString(string APIKey, string url, string method, string bodyContent = null)
{
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = method;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization", "Basic " + APIKey);
switch (method)
{
case "GET":
case "DELETE":
WebResponse httpResponseGETDELETE = await httpWebRequest.GetResponseAsync();
using (StreamReader streamReader = new StreamReader(httpResponseGETDELETE.GetResponseStream()))
{
string result = await streamReader.ReadToEndAsync();
return result;
}
case "POST":
case "PUT":
case "PATCH":
using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
await streamWriter.WriteLineAsync(bodyContent);
await streamWriter.FlushAsync();
streamWriter.Close();
WebResponse httpResponsePOSTPUT = await httpWebRequest.GetResponseAsync();
using (StreamReader streamReader = new StreamReader(httpResponsePOSTPUT.GetResponseStream()))
{
string result = await streamReader.ReadToEndAsync();
return result;
}
}
default:
return "Method Not Found!";
}
}
catch (Exception e)
{
return e.Message;
}
}
它甚至没有泡到捕获线。它只是关闭应用程序。
当我在Fiddler中观看网络流量时,我可以看到它试图打开https连接但是它会停止。
这就是我在Fiddler看到的:
我完全难以理解如何在没有错误消息的情况下找到根本原因?
更新
我现在使用HttpClient重写了我的代码,它现在在以下行中失败了:
HttpResponseMessage response = await client.PostAsync(url, content);
在此代码中:
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Basic " + APIKey);
StringContent content = new StringContent(bodyContent, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
return await response.Content.ReadAsStringAsync();
}
答案 0 :(得分:0)
好的 - 这是我的错。
在我使用的控制台应用程序中:
SyncEngine.Functions.Sync("APIKey1", "APIKey2");
当我应该使用时:
SyncEngine.Functions.Sync("APIKey1", "APIKey2").GetAwaiter().GetResult();
对不起家伙