2017-10-18 163 views
0

我想創建一個控制器,可以響應這些請求:的Web API路由{控制器}/{行動}/{ID} VS默認路由

  1. API /用戶/ 123
  2. API /用戶/ UsersOfCompany?ID = 123 &的PageIndex = 0 &的pageSize = 20
  3. 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以上,我想路由的工作是這樣的:

  1. Get(int id)
  2. UsersOfCompany(int id, [FromUri] Paging paging)
  3. 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電話工程和其他兩隻時卻。

問題在哪裏?

+2

什麼,你問我們找到問題?是否有錯誤訊息?如果是這樣,它發生在何時何地? – NightOwl888

+0

對不起...更新了這個問題! :-) –

回答

3

您的錯誤消息清楚地表明WebApi試圖匹配Service/api/User/123到第一個模式:api/{controller}/{action}/{id}

你可以試着改變註冊的順序在WebApiConfig或顯式地指定路線:

[Route("api/User/{id:int}")] 
[HttpGet] 
public IHttpActionResult Get(int id) 
{ 
    //... implementation... 
}