This is my learning phase of Web API. I have created one sample Web API application in which I have used serialization(xml/json). All is working fine if I make a request form Rest Client of Firefox.
But now I am requesting from console application using HTTPCLIENT & HttpResponseMessage.
Here is my method in Console:
public void GetData()
{
HttpClient cons = new HttpClient();
cons.BaseAddress = new Uri("http://localhost:50524/");
cons.DefaultRequestHeaders.Accept.Clear();
cons.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
MyAPIGet(cons).Wait();
}
static async Task MyAPIGet(HttpClient cons)
{
using (cons)
{
HttpResponseMessage res = await cons.GetAsync("api/Authors/GetAuthor/1");
res.EnsureSuccessStatusCode();
if (res.IsSuccessStatusCode)
{
// Books book = await res.Content.ReadAsAsync<Books>();
Author author = await res.Content.ReadAsAsync<Author>();
Console.WriteLine("\n");
Console.WriteLine("---------------------Calling Get Operation------------------------");
Console.WriteLine("\n");
Console.WriteLine("authorId authorName BookId");
Console.WriteLine("-----------------------------------------------------------");
Console.WriteLine("{0}\t{1}\t\t{2}", author.Id, author.Name, author.BookId);
Console.ReadLine();
}
}
}
Error:
{"Error converting value \"{\"Id\":1,\"Name\":\"Ankita\",\"BookId\":1,\"Books\":[]}\" to type 'WebAPI_ConsumerConsole.Domain.Author'. Path '', line 1, position 58."}
Here is my method in Web API:
public IHttpActionResult GetAuthor(int id)
{
Author author = db.Authors.Find(id);
if (author == null)
{
return NotFound();
}
return Ok(author);
}
If I return author from service method Error I got in console:
{"Error in line 1 position 69. Expecting element 'Author' from namespace 'http://schemas.datacontract.org/2004/07/WebAPI_ConsumerConsole.Domain'.. Encountered 'Element' with name 'string', namespace 'http://schemas.microsoft.com/2003/10/Serialization/'. "}