【发布时间】:2014-07-29 21:34:16
【问题描述】:
我的 ASP.NET web api 有两个功能:一个返回所有产品的列表,另一个返回一个取决于条件的列表。
public class ProductsController : ApiController
{
List<Product> lst = new List<Product>
{
new Product(){ Id = 1, Name = "a Soup", Category = "Groceries", Price = 1 },
new Product(){Id = 2, Name = "b Soup", Category = "stat", Price = 4 },
new Product(){ Id = 3, Name = "c Soup", Category = "Groceries", Price = 1 }
};
public List<Product> GetAllProducts()
{
return lst;
}
public List<Product> GetProducts(int k)
{
return lst.Where(p => p.Price == k).ToList();
}
}
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
我正在使用 jQuery 的 GET 方法,如下所示:
<script type="text/javascript">
function getProducts() {
$.getJSON("api/products/1",
function (data) {
debugger;
});
}
$(document).ready(getProducts);
</script>
这个函数会调用第一个函数,即 GetAllProducts,即使我通过调用它来调用它
"api/products/1"
我的问题是它如何确定从客户端调用时调用哪个函数?
【问题讨论】:
-
你检查你的
RouteConfig.cs文件了吗? -
嗨罗伯特,刚刚更新了路由配置
-
如果你用
console.log(data);代替调试器并检查响应? -
我得到了 3 个对象而不是一个
-
根据默认路由设置..你应该有4个方法(GET,POST,PUT,DELETE)。如果要调用自己的方法,需要在 route.config 文件中指定自定义路由。