为什么这个Web Api路由不起作用?

时间:2015-06-30 15:13:17

标签: url-routing asp.net-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);
    }
}

我不明白为什么这些路线有效:

但是这个没有:

2 个答案:

答案 0 :(得分:0)

在get方法的基础上添加路由属性。

private void SelectionChangedExecuted(object datasets)
{
    this.selectedDatasets = new List<ObservableDataset>((datasets as IList).Cast<ObservableDataset>());
}

答案 1 :(得分:0)

部分问题是您在RouteConfig中注册了Api路由而不是WebApiConfig。 从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