我想創建一個控制器,可以響應這些請求:的Web API路由{控制器}/{行動}/{ID} VS默認路由
- API /用戶/ 123
- API /用戶/ UsersOfCompany?ID = 123 &的PageIndex = 0 &的pageSize = 20
- API /用戶/ AllowedCompanies?ID = 123 &的PageIndex = 0 &的pageSize = 10
這是我的實際代碼。
用戶控制器
public class UserController : ApiController
{
[HttpGet]
public IHttpActionResult Get(int id)
{
//... implementation...
}
[HttpGet]
[ActionName("UsersOfCompany")]
public IHttpActionResult UsersOfCompany(int id, [FromUri] Paging paging)
{
//... implementation...
}
[HttpGet]
[ActionName("AllowedCompanies")]
public IHttpActionResult AllowedCompanies(int id, [FromUri] Paging paging)
{
//... implementation...
}
}
WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Servizi e configurazione dell'API Web
// Route dell'API Web
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ApiWithActionName",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.MessageHandlers.Add(new LanguageMessageHandler());
}
}
RouteConfig
public class RouteConfig
{
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 }
);
}
}
基於樣品熱曲EST以上,我想路由的工作是這樣的:
Get(int id)
UsersOfCompany(int id, [FromUri] Paging paging)
AllowedCompanies(int id, [FromUri] Paging paging)
但是,現在,我只能打電話過去2個請求(UsersOfCompany,AllowedCompanies)。 當我打電話API /用戶/ 123我得到這個錯誤:
"Could not find an HTTP resource that matches the request's URL 'Service/api/User/123'.", "Unable to find an action on the 'User' controller with name '42887'."
我已經試圖反轉路線登記的先後順序,但我otained相反的行爲,使api/User/123
電話工程和其他兩隻時卻。
問題在哪裏?
什麼,你問我們找到問題?是否有錯誤訊息?如果是這樣,它發生在何時何地? – NightOwl888
對不起...更新了這個問題! :-) –