문제

I started a new Web Api MVC4 project and am having no luck figuring out what I am doing wrong with the routers. My routes for simple Get requests are returning 404.

Here are my route definitions:

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

        routes.MapRoute("ApiDefault", "api/{controller}/{id}",
                        new {controller = "Home", id = UrlParameter.Optional});

        routes.MapRoute("ApiDefault-CategoryLevels", "api/{controller}/{level1}/{level2}/{level3}/{level4}",
                        new
                            {
                                controller = "Home",
                                level1 = UrlParameter.Optional,
                                level2 = UrlParameter.Optional,
                                level3 = UrlParameter.Optional,
                                level4 = UrlParameter.Optional
                            });

        routes.MapRoute("Default", "{controller}/{action}/{id}",
                        new {controller = "Home", action = "Index", id = UrlParameter.Optional});
    }

I am trying to get the ApiDefault-CategoryLevels route to be used. I installed Phil Haack's routing debugger and it is showing that when I browse to this Url:

http://localhost:22283/api/Categories/a/b/c/d

that the route I am looking for IS matching:

Matched Route: api/{controller}/{level1}/{level2}/{level3}/{level4}

Route       Data
Key         Value
controller  Categories 
level1      a 
level2      b 
level3      c 
level4      d

However the return from the IIS Webserver is a 404.

When I call the same URL in this manner, using a querystring, it works:

http://localhost:22283/api/Categories?level1=A&level2=B&level3=C&level4=D

The web request works and I get back the results I was expecting. It is only when I try the request the first way does it return a 404.

Here is the entirety of my CategoriesController:

public class CategoriesController : ApiController
{

    public IEnumerable<CategoryModel> Get(string level1 = null, string level2 = null, string level3 = null, string level4 = null)
    {
        return new[] {new CategoryModel()};
    }

    public CategoryModel Get(Guid id)
    {
        return new CategoryModel();
    }
}
도움이 되었습니까?

해결책

You are adding your ApiController-based routes to RouteTable.Routes. You should be adding them to GlobalConfiguration.Configuration. That is, it appears you have added them to the MVC 4 project template's RouteConfig.RegisterRoutes(RouteCollection). If you use the MVC4 Web API project template, add them to the WebApiConfig.Register(HttpConfiguration) method, instead.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top