我曾经使用ASMX Web服务,但是自从读取(并被告知)从客户端请求数据的更好方法是使用带有MVC的Web API。从客户端应用程序调用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());
}
}
}
在调试我可以通过步骤请求并成功输入网页API代码 -
Product product = await response.Content.ReadAsAsync<Product>();
这失败了,进入我的渔获,除了 -
Error converting value "value" to type 'myDemo.Home+Product'. Path '', line 1, position 7.
这是为什么?
因为它是一个'String',而不是'Product'。 –