2016-12-07 79 views
-1

我不知道如何在瀏覽器中查看get api結果。我試圖讓這個網址(http://localhost:8269/api/getproducts)的響應,但得到一個錯誤:無法獲取webapi結果

<Error> 
    <Message> 
     No HTTP resource was found that matches the request 
     URI 'http://localhost:8269/api/getProducts'. 
    </Message> 
    <MessageDetail> 
     No type was found that matches the controller named 'getProducts'. 
    </MessageDetail> 
</Error> 
public class ProductsController : ApiController 
{ 
    Product[] products = new Product[] 
    { 
     new Product { ProductId=1,ProductName="samsung",ProductCategory="mobile",ProductPrice=7889 }, 
     new Product { ProductId=1,ProductName="nokia",ProductCategory="mobile",ProductPrice=7844 }, 
     new Product { ProductId=1,ProductName="lg",ProductCategory="mobile",ProductPrice=7887 }, 
     new Product { ProductId=1,ProductName="xiomi",ProductCategory="mobile",ProductPrice=7856 }, 
     new Product { ProductId=1,ProductName="htc",ProductCategory="mobile",ProductPrice=7833 } 
    }; 

    public IEnumerable getProducts() 
    { 
     return products; 
    } 
} 
+0

你試過 - http:// localhost:8269/api/products/getproducts? – Manoj

+0

是的我試過了,出現錯誤('ObjectContent'1'類型未能序列化內容類型'application/xml; charset = utf-8'的響應正文)。 – Swapna

+0

請編輯你的ajax方法,你必須設置ContentType :應用程序/ XML中的Ajax請求? – Manoj

回答

3

你的URI應該是'http://localhost:8269/api/Products'(使用默認路由是...)

當您使用的是Web API 2,您的示例應該可以正常使用上述網址。 使用Web API 1時,雖然只需調用Get()或使用[HttpGet]屬性修飾您的方法。

[HttpGet] 
public IEnumerable getProducts() 
{ 
    return products; 
} 

我建議你看看asp.net web apithis answer基本有點接近。

+0

還值得關注其他資源命名的基礎 - http://www.restapitutorial.com/lessons/restfulresourcenaming.html –