首先创建一个项目,web-----》webapi----控制器添加一个控制器ProductsController
不多说直接上代码:
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
//
// GET: /Products/
public IEnumerable<Product> GetAllProducts()
{
return products;
}
public Product GetProductById(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return product;
}
public IEnumerable<Product> GetProductsByCategory(string category)
{
return products.Where(p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));
}
}
好的代码编写完成:调试。。。。。
那么问题来了:请求的url http://localhost:32873/Products/GetProductById?id=1
居然报了一个404错误
修改地址http://localhost:32873/api/Products/GetProductById?id=1,终于出来了
好换个方法试试:
http://localhost:32873/api/Products/GetAllProducts
抛出异常了,说id不能为空,咋还是GetProductById这个方法呢?我调用的是GetAllProducts这个方法呀,别着急问题终会解决的
app-Start下有一个设置路由的类WebApiConfig.cs
将路由改为以下内容完美运行,
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "Products",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// 取消注释下面的代码行可对具有 IQueryable 或 IQueryable<T> 返回类型的操作启用查询支持。
// 若要避免处理意外查询或恶意查询,请使用 QueryableAttribute 上的验证设置来验证传入查询。
// 若要在应用程序中禁用跟踪,请注释掉或删除以下代码行
//config.EnableSystemDiagnosticsTracing();
}
}
哎终于大功告成了。