1

我正在创建一个使用 Web API 的演示移动应用程序。我关注这个网站:

这就是我调用 Web API 的方式:

class Program
    {
        static void Main(string[] args)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:9000/");

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
        }
    }

这就是调用 API 函数的方式:

HttpResponseMessage response = client.GetAsync("api/products").Result;  // Blocking call!
if (response.IsSuccessStatusCode)
{
    // Parse the response body. Blocking!
    var products = response.Content.ReadAsAsync<IEnumerable<Product>>().Result;
    foreach (var p in products)
    {
        Console.WriteLine("{0}\t{1};\t{2}", p.Name, p.Price, p.Category);
    }
}
else
{
    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}

我不明白这一行:

HttpResponseMessage response = client.GetAsync("api/products").Result;    

api/products使用地址时叫什么?API 的模型、控制器类或其他任何东西?

4

2 回答 2

0

The answer to your question is in the first page you referenced:

To get the list of all products, add this method to the ProductsController class:

public class ProductsController : ApiController
{
    public IEnumerable<Product> GetAllProducts()
    {
        return repository.GetAll();
    }
    // ....
}

The method name starts with "Get", so by convention it maps to GET requests. Also, because the method has no parameters, it maps to a URI that does not contain an "id" segment in the path.

So, the call to

HttpResponseMessage response = client.GetAsync("api/products").Result;

will call the products controller's function that starts with Get and that has no parameter.

If you are not familiar with controllers, you can learn more about the MVC pattern on the ASP.NET MVC Overview.

于 2013-11-07T08:46:38.347 回答
0

HttpResponseMessage response = client.GetAsync("api/products").Result表示向作为 API 控制器的 Product 控制器发送请求。产品控制器处理您的请求后,将其结果存储在 HttpResponseMessage 的实例中。

如果放置断点,您将看到响应包含产品列表(我假设这是 Product 控制器所做的)。

于 2013-11-07T12:10:38.823 回答