2015-06-30 62 views
0

我說過這些路線和控制器:爲什麼這個Web Api路由不工作?

public class RouteConfig 
{ 
    public static readonly string MVC_ROUTING = "Default"; 
    public static readonly string WEB_API_ROUTING = "Api"; 

    public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
     routes.MapRoute(
      name: MVC_ROUTING, 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, 
      constraints: new { id = @"^[0-9]*$" } 
    ); 

     routes.MapRoute(
      name: WEB_API_ROUTING, 
      url: "api/{controller}/{action}/{id}", 
      defaults: new {id = UrlParameter.Optional }, 
      constraints: new { id = @"^[0-9]*$" } 
    ); 
    } 
} 

public class QuoteController : ApiController 
{ 
    private readonly QuoteService quoteService; 
    public QuoteController() 
    { 
     quoteService = new QuoteService(); 
    } 

    // GET api/<controller> 
    public IEnumerable<QuoteModel> Get() 
    { 
     return quoteService.GetAllQuotes().Map<QuoteModel>(); 
    } 

    // GET api/<controller>/5 
    public QuoteModel Get(int id) 
    { 
     return quoteService.GetQuoteById(id).Map<QuoteModel>(); 
    } 

    // POST api/<controller> 
    public HttpResponseMessage Post(QuoteModel quoteModel) 
    { 
     Quote quote = quoteModel.Map<Quote>(); 
     quoteService.AddNewQuote(quote); 

     string uri = Url.Link(RouteConfig.WEB_API_ROUTING, new { id = quote.QuoteId,controller="Quote",action="Get"}); 
     return Request.CreateResponse(HttpStatusCode.OK, uri); 
    } 

    // PUT api/<controller>/5 
    public void Put(QuoteModel quote) 
    { 
     quoteService.Update(quote.Map<Quote>()); 
    } 

    // DELETE api/<controller>/5 
    public void Delete(int id) 
    { 
     quoteService.DeleteQuote(id); 
    } 
} 

我不明白爲什麼這些路線工作:

但是這一次沒有:

回答

0

部分是已註冊的RouteConfig而非WebApiConfig您的API路線。 從RouteConfig中刪除Web Api路由,然後打開WebApiConfig。

您可能已經在WebApiConfig中有一個默認路由;在那裏更改路線如下:

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
     config.Routes.MapHttpRoute(
      name: "Api", 
      routeTemplate: "api/{controller}/{action}/{id}", 
      defaults: new { id = RouteParameter.Optional }, 
      constraints: new { id = @"\d*", action = @"[a-zA-Z]+" } 
     ); 

     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional }, 
      constraints: new { id = @"\d*" } 
     ); 
    } 
} 

您現在應該能夠擊中上面列出的所有路線。 更好的選擇是使用屬性路由,您可以閱讀關於here的內容。

+0

非常感謝你,它完美的作品 –

0

添加一個路由屬性,在你的get方法的頂部。問題的

[Route("{id}")] 
public QuoteModel Get(int id) 
{ 
    return quoteService.GetQuoteById(id).Map<QuoteModel>(); 
}