Ebikeneser
Ebikeneser

Reputation: 2364

Call web API from client app

I used to use ASMX web services, however have since read (and been told) that a better way to request data from a client etc is to use web API's with MVC.

I have created an MVC 4 web api application and getting to grips with how it works.

Currently I have a single public string in my valuesControllers -

public class ValuesController : ApiController
{


    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }

}

And I am currently trying to call this in my client like this -

class Product
    {
        public string value { get; set; }
    }

protected void Button2_Click(object sender, EventArgs e)
    {
        RunAsync().Wait();
    }

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            try
            {
                client.BaseAddress = new Uri("http://localhost:12345/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // HTTP GET
                HttpResponseMessage response = await client.GetAsync("api/values/5");
                if (response.IsSuccessStatusCode)
                {
                    Product product = await response.Content.ReadAsAsync<Product>();
                    Console.WriteLine("{0}", product.value);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
        }
    }

On debugging I can step through the request and enter the web API code successfully however on the line -

Product product = await response.Content.ReadAsAsync<Product>();

This fails and enters my catch with the exception -

Error converting value "value" to type 'myDemo.Home+Product'. Path '', line 1, position 7.

Why is this?

Upvotes: 2

Views: 952

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Why is this?

Because from your controller action you are returning a string, not a Product which are 2 quite different types:

public string Get(int id)
{
    return "value";
}

so make sure that you are consistently reading the value on the client:

if (response.IsSuccessStatusCode)
{
    string result = await response.Content.ReadAsAsync<string>();
    Console.WriteLine("{0}", result);
}

Of course if you modified your API controller action to return a Product:

public Product Get(int id)
{
    Product product = ... go fetch the product from the identifier
    return product;
}

your client code would work as expected.

Upvotes: 4

Related Questions