I am trying to setup and consume an asp.net webapi rest application and consume it from another project.
I have made a simple helper to call the service like
public static string GetApiResponse(string apiMethod,Dictionary<string,string>queryString=null)
{
using (var client = new WebClient())
{
client.Headers.Add("ApiKey", ConfigurationManager.AppSettings["ApiKey"]);
//add any query string values into the client
if (queryString != null)
{
foreach (var query in queryString)
{
client.QueryString.Add(query.Key, query.Value);
}
}
try
{
string url = string.Format("{0}{1}", ConfigurationManager.AppSettings["ApiBaseUrl"],apiMethod);
return(client.DownloadString(url));
}
catch (Exception ex)
{
return ex.Message;
}
}
}
I am consuming it from my controller in a different project like
private IEnumerable<CustomerModel> CustomerDetails()
{
var json = ApiRestHelper.GetApiResponse("Customer/Get");
var data = JsonConvert.DeserializeObject<CustomerViewModel>(json, new JsonSerializerSettings
{
});
The returned data from the service is looking like
[{"CustomerId":"24a62bf8-7a4e-4837-859d-1f04dc983011","FirstName":"Joe","LastName":"Bloggs","StoreCustomerId":null}]
My CustomerViewModel is
public class CustomerViewModel
{
public IEnumerable<CustomerModel> Customers { get; set; }
}
I can see the data that is returned is an array and I am trying to convert it to the list. I get an error
Cannot deserialize JSON array (i.e. [1,2,3]) into type ‘WebApplication.Models.ViewModels.CustomerViewModel’.
The deserialized type must be an array or implement a collection interface like IEnumerable, ICollection or IList.
What do I need to change to allow the deserialization into my view model?
I was trying to do it wrong.
Does the trick