0

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/'. "}

Ankita
  • 1,416
  • 4
  • 17
  • 42
  • you know that serialization can be done automatically? Just return `Ok(author);` from web api action – Aleksey L. Jul 07 '16 at 06:44
  • Yes, that is working fine. But as per my knowledge it is returning in xml. What I need to do to return in json form? Moreover, can you please tell me why we need serialization? In which situation? – Ankita Jul 07 '16 at 06:46
  • No, it returns result according to client's request `Accept` header – Aleksey L. Jul 07 '16 at 06:48
  • Can you please tell me why we need serialization? In which situation? – Ankita Jul 07 '16 at 06:48
  • We always need serialization, but we don't need to do it manually - framework can handle this for us – Aleksey L. Jul 07 '16 at 06:51
  • Yeah. I have just read this: "The framework inserts these formatters into the pipeline by default." Thank you. – Ankita Jul 07 '16 at 06:52
  • And what about other error. If I pass XML in header. It gives me error too. – Ankita Jul 07 '16 at 06:54
  • Looks like you are double-serializing your JSON and XML. See [Strings sent through Web API's gets wrapped in quotes](https://stackoverflow.com/questions/33681978/strings-sent-through-web-apis-gets-wrapped-in-quotes). – dbc Jul 07 '16 at 07:25
  • Sorry but are you talking about second error which I got if I use XML as a header – Ankita Jul 07 '16 at 07:55
  • For both JSON and XML the error seems to indicate that your returned `Author` was serialized to a string, then the string double-serialized as a string literal in another string. – dbc Jul 07 '16 at 07:59
  • I have updated my GetAuthor method. It is working fine if I use header json. But with xml still getting an error. – Ankita Jul 07 '16 at 09:40

0 Answers0