2013-12-12 28 views
1

所以我有以下的控制:如何使用URL將參數設置爲FromURI?

public class ItemQuery { 
    public int storeID { get; set; } 
    public int companyID { get; set; } 
    public string itemName { get; set; } 
    public string itemDescription { get; set; } 
    public string itemPLU { get; set; } 
    public string itemUPC { get; set; } 
    public int supplierID { get; set; } 
    public string partNumber { get; set; } 
} 
public class ItemController : ApiController { 
    public List<Item> FindItem([FromUri]ItemQuery query) { 
     return new List<Item>(); 
    } 

} 

我想這個要求打:

http://localhost:43751/api/Item/Find?query[storeID]=1 

而且這不是工作,但給我這個錯誤:

The requested resource does not support http method 'GET'. 

我該怎麼辦?這裏是我的路由信息​​,我並沒有改變任何東西:

public static void RegisterRoutes(RouteCollection routes) { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 
    } 

回答

2

我認爲你應該確保你使用Web Api的System.Web.Http命名空間。

然後改變方法名GetFindItem或添加HttpGet屬性,象下面這樣:

[HttpGet] 
public List<Item> FindItem([FromUri]ItemQuery query){ // } 

而且您的查詢字符串應該是象下面這樣:

http://localhost:43751/api/Item/?storeId=1&companyID=2&itemName=ABC&itemDescription=good&itemPLU=aa&itemUPC=dd&&supplierID=1&partNumber=number 

如果您使用的Ajax調用Web API,下面是一個例子

Js文件

var data = { 
    storeID: 1, 
    companyID: 1, 
    itemName: 'Test', 
    itemDescription: 'Description', 
    itemPLU: 'Test', 
    itemUPC: 'Test', 
    supplierID: 1, 
    partNumber: 'Description', 
}; 
$.getJSON('/api/Item', { query:data }, function() { 
     alert("success"); 
}); 
+0

剛剛嘗試過,效果非常好! – Bill

0

您還沒有定義的WebAPI路由。

你所擁有的routes.MapRoute是MVC。要定義WebApi的路由,你將需要使用routes.MapHttpRoute

+0

你能提供代碼示例嗎? – Bill

相關問題