从客户端应用程序调用Web API

时间:2014-03-03 16:21:34

标签: c# asp.net-mvc asp.net-web-api

我曾经使用ASMX Web服务,但是从那时起(并被告知)从客户端等请求数据的更好方法是使用带有MVC的Web API。

我创建了一个MVC 4 web api应用程序,并开始掌握它的工作原理。

目前我在valuesControllers中有一个公共字符串 -

public class ValuesController : ApiController
{


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

}

我目前正试图在我的客户端中这样说 -

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());
            }
        }
    }

在调试时,我可以单步执行请求并成功输入Web API代码 -

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

此操作失败,并以异常 -

输入我的捕获
Error converting value "value" to type 'myDemo.Home+Product'. Path '', line 1, position 7.

为什么会这样?

1 个答案:

答案 0 :(得分:4)

  

为什么会这样?

因为您从控制器操作中返回的是string,而不是Product,这两种类型完全不同:

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

因此请确保您始终在客户端上阅读该值:

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

当然,如果您修改了API控制器操作以返回产品:

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

您的客户端代码将按预期工作。