Search code examples
c#asp.net-mvcasp.net-routing

ASP.NET MVC Routing doesn't work with a prefix "api"


I'm new to the mvc, here I'm trying to add the api prefix in the URL pattern followed by controller, action and id.

But things does not work as I expected.

I have a controller named "Activity", with a method "Query"

public class ActivityController : Controller
{
    ...

    [HttpGet]
    public JsonResult Query(int limit = DEFAULT_LIMIT,
        int offset = DEFAULT_OFFSET)
    {
        repository.apiInfo.data = repository.readActivities(limit, offset);

        return Json(repository.apiInfo , 
            JsonRequestBehavior.AllowGet);
    }
    ...
}

And I define a route mapping rule to try to invoke Query(), like:

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

    routes.MapRoute(
        name: "MyRule",
        url: "api/{controller}/{action}/{id}",
        defaults: new { controller = "Activity", action = "Query", id = UrlParameter.Optional }
    );
}

I've made sure it's registered at the Application_Start() method, as well as it works well without the api prefix.

But it turns out to show the message

"Cannot find the url 'http://localhost:49571/api'"
"Cannot find the Activity controller."

Please tell me where did I miss out.


Solution

  • You most probably already have Web API enabled, whose routes are registered before MVC route. That means that any calls prefixed with api is being routed to your web api as first match wins in the route table.

    Look for the following class in the project

    public static class WebApiConfig {
        public static void Register(HttpConfiguration config) {
            // Attribute routing.
            config.MapHttpAttributeRoutes();
    
            // Convention-based routing.
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
    

    Note the DefaultApi route.

    Either remove the above route or change the route being used by the MVC route collection.