我是HttpClient和Web API的新手,所以我确信我错过了其他人明显的东西。我正在尝试使用新员工列表调用第三方Web API。 API应该返回JSON,其中包含有关上载员工的信息。这将是一个控制台应用程序,将每晚运行一次。没有要求运行Async。
我正在尝试跟随这些文章。 http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client 和 http://typecastexception.com/post/2013/07/03/Building-Out-a-Clean-REST-ful-WebApi-Service-with-a-Minimal-WebApi-Project.aspx
以下代码尝试将API结果放入数组或列表中,但无法正常工作。当我在Debug中运行它时,它给了我一个例外“发生了一个或多个错误。”这并没有给我很多东西继续。
if (response.IsSuccessStatusCode)
{
AddEmployeeResult employeeResults = response.Content.ReadAsAsync<AddEmployeeResult>().Result;
}
供应商给了我这个作为应该返回的例子。
[{"EmployeeNumber":"22449","SuccessfullyAdded":true,"Existing":false,"Comments":"App UserId: 6037"},{"EmployeeNumber":"379844","SuccessfullyAdded":true,"Existing":false,"Comments":" App UserId: 6038"},{"EmployeeNumber":"23718","SuccessfullyAdded":true,"Existing":false,"Comments":" App UserId ps: 6039"}]
我在我的控制台应用程序中创建了一个类,以匹配应该从API返回的内容。
class AddEmployeeResult
{
public string EmployeeNumber { get; set; }
public bool SuccessfullyAdded { get; set; }
public bool Existing { get; set; }
public string Comments { get; set; }
}
这是我正在尝试的代码。
static void Main(string[] args)
{
UploadNewEmployee();
}
public static void UploadNewEmployee()
{
string serviceURI = "https://services.website.com/api/employees/upload";
var credentials = new NetworkCredential("username", "password");
var clientHandler = new HttpClientHandler();
clientHandler.Credentials = credentials;
clientHandler.PreAuthenticate = true;
//*** Get the Employee Data ***
List<Employee> lstEmployee = new List<Employee>();
try
{
lstEmployee = DataManager.GetEmployees();
}
catch (Exception ex)
{
logger.Error("Error while getting data. | {0} | Trace: {1}", ex.Message, ex.StackTrace);
}
//*** Process users if there is data. ***
if (lstEmployee != null && lstEmployee.Count > 0)
{
logger.Info("Employee count: " + lstEmployee.Count);
logger.Debug("Web API Uri: " + serviceURI);
try
{
using (var client = new HttpClient(clientHandler))
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync(serviceURI, lstEmployee).Result;
if (response.IsSuccessStatusCode)
{
AddEmployeeResult employeeResults = response.Content.ReadAsAsync<AddEmployeeResult>().Result;
}
}
}
catch (Exception ex)
{
logger.Error("Error posting to Web API. | {0} | Trace: {1}", ex.Message, ex.StackTrace);
}
}
else
{
logger.Info("No records found.");
}
}