如何将web api用作Web服务?

我已经创建了一个测试ASP.Net Web Api,现在我想知道如何在Windows窗体应用程序中将它用作Web服务?

当前url为http://localhost:59682 ,当我添加http://localhost:59682http://localhost:59682/api/http://localhost:59682/api/products/作为网络服务参考时我收到此错误: There was an error downloading 'http://localhost:59682/api/products/$metadata'. The request failed with HTTP status 400: Bad Request. Metadata contains a reference that cannot be resolved: 'http://localhost:59682/api/products/'. The remote server returned an unexpected response: (405) Method Not Allowed. The remote server returned an error: (405) Method Not Allowed. If the service is defined in the current solution, try building the solution and adding the service reference again. There was an error downloading 'http://localhost:59682/api/products/$metadata'. The request failed with HTTP status 400: Bad Request. Metadata contains a reference that cannot be resolved: 'http://localhost:59682/api/products/'. The remote server returned an unexpected response: (405) Method Not Allowed. The remote server returned an error: (405) Method Not Allowed. If the service is defined in the current solution, try building the solution and adding the service reference again.

这是我的web.config:

      

这是我的ProductsController

 using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using WebApiLearning.Models; namespace WebApiLearning.Controllers { public class ProductsController : ApiController { Product[] products = new Product[] { new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1.39M }, new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } }; public IEnumerable GetAllProducts() { return products; } public Product GetProductById(int id) { var product = products.FirstOrDefault((p) => p.Id == id); if (product == null) { var resp = new HttpResponseMessage(HttpStatusCode.NotFound); throw new HttpResponseException(resp); } return product; } public IEnumerable GetProductsByCategory(string category) { return products.Where( (p) => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase)); } } } 

这是Product型号:

 using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApiLearning.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } } } 

您无法向Web Api添加服务引用,因为它只是一个允许您通过HTTP公开function的框架(基本上您在控制器上调用方法)。

我建议你安装Web API客户端库

看看下面的链接

http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client