[英]ASP.NET Web Api Routing not working in C#
[英]asp.net Web Api routing not working
這是我的路由配置:
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
而且,這是我的控制器:
public class ProductsController : ApiController
{
[AcceptVerbs("Get")]
public object GetProducts()
{
// return all products...
}
[AcceptVerbs("Get")]
public object Product(string name)
{
// return the Product with the given name...
}
}
當我嘗試api/Products/GetProducts/
,它可以工作。 api/Products/Product?name=test
也有效,但是api/Products/Product/test
不起作用。 我究竟做錯了什么?
更新:
這是我在嘗試api/Products/Product/test
:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:42676/api/Products/Product/test'.",
"MessageDetail": "No action was found on the controller 'Products' that matches the request."
}
這是因為您的路由設置及其默認值。 你有兩個選擇。
1)通過更改路由設置以匹配Product()參數以匹配URI。
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{name}", // removed id and used name
defaults: new { name = RouteParameter.Optional }
);
2)另一種推薦的方法是使用正確的方法簽名屬性。
public object Product([FromUri(Name = "id")]string name){
// return the Product with the given name
}
這是因為該方法在請求api / Products / Product / test時期望參數id ,而不是查找name參數。
根據您的更新:
請注意, WebApi基於反射工作,這意味着您的花括號{vars}必須與方法中的相同名稱匹配。
因此,要根據此模板匹配此api/Products/Product/test
"api/{controller}/{action}/{id}"
您需要聲明這樣的方法:
[ActionName("Product")]
[HttpGet]
public object Product(string id){
return id;
}
其中參數string name
由string id
替換。
這是我的完整樣本:
public class ProductsController : ApiController
{
[ActionName("GetProducts")]
[HttpGet]
public object GetProducts()
{
return "GetProducts";
}
[ActionName("Product")]
[HttpGet]
public object Product(string id)
{
return id;
}
}
我嘗試使用完全不同的模板:
config.Routes.MapHttpRoute(
name: "test",
routeTemplate: "v2/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional, demo = RouteParameter.Optional }
);
但它在我的結尾工作得很好。 順便說一句我另外刪除[AcceptVerbs("Get")]
並用[HttpGet]
替換它們
您的路由是將id定義為參數,但您的方法需要name參數。 如果可以,我更喜歡屬性路由,然后在Product方法上定義/ api / products / product / {name}。
http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.