2016-11-10 32 views
1

我不知道如何命名此問題。由於這個原因,我也很難搜索這個特定的問題。我找到的最匹配的問題是Web Api Routing conflict for two different controllers?Web API路由衝突時添加PUT方法到子路由,與多個控制器

像這一問題的提問者,我也有兩個不同的控制器,部分匹配:

public class JobsController : ApiController 
{ 
    [ResponseType(typeof(DTJob[]))] 
    public async Task<HttpResponseMessage> Get() 
    { 
     //... 
    } 

    [Route("v1/Jobs/Group"), ResponseType(typeof(DTJob[]))] 
    public async Task<HttpResponseMessage> GetFromGroup() 
    { 
     //... 
    } 

    [HttpGet, Route("v1/Jobs/{jobId}/Status"), ResponseType(typeof(string))] 
    public async Task<HttpResponseMessage> GetStatus(long jobId) 
    { 
     //... 
    } 

    [HttpPut, Route("v1/Jobs/{jobId}/Status"), ResponseType(typeof(void))] 
    public async Task<HttpResponseMessage> UpdateStatus(long jobId, string status) 
    { 
     //... 
    } 

    //This method messes up all other controllers 
    [HttpPut, Route("v1/Jobs/{jobId}"), ResponseType(typeof(void))] 
    public async Task<HttpResponseMessage> Put(long jobId, DTJob job) 
    { 
     //... 
    } 

    //But it works if I replace the above method with the default routing pattern: 
    //[ResponseType(typeof(void))] 
    //public async Task<HttpResponseMessage> Put(long id, DTJob job) 
    //{ 
    // //... 
    //} 
} 

而且具有相似的前綴另一個控制器:

[RoutePrefix("v1/Jobs/Materials")] 
public class MaterialsController : ApiController 
{ 
    [Route, ResponseType(typeof(DTMaterial[]))] 
    public async Task<HttpResponseMessage> Get() 
    { 
     //... 
    } 
} 

我的路由CONFIGS:

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

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
     //... 
     // Web API routes 
     config.MapHttpAttributeRoutes(); 
     //... 
     config.Routes.MapHttpRoute(
      name: "Newest", 
      routeTemplate: "v1/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 
    } 
} 

這是怎麼回事?

回答

0

我想我再次發現了這個問題。由於{jobId}沒有在類型中指定,因此它可能是一個字符串,它會顯示「材質」,從而產生衝突。爲了解決這個問題,我可以在參數中指定類型({jobId:long}):

[HttpPut, Route("v1/Jobs/{jobId:long}"), ResponseType(typeof(void))] 
    public async Task<HttpResponseMessage> Put(long jobId, DTJob job) 
    { 
     //... 
    }