简体   繁体   中英

MVC Web Api Route with default action not working

In my TestController I have the following:

 [HttpGet]
    public IEnumerable<String> Active()
    {
        var result = new List<string> { "active1", "active2" };

        return result;
    }

    [HttpGet]
    public String Active(int id)
    {
        var result = new List<string> { "active1", "active2" };

        return result[id];
    }

In RouteConfig the mapping is:

 routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        routes.MapHttpRoute(
            name: "ActionApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { action = "", id = RouteParameter.Optional });

In a browser the following request works:

api/test/active/1

But this returns a Internal Server Error :

api/test/active

What do you have to do to return a action that may or maynot have a parameter in a similar manner to the default Get?

Update 1 As Cuong Le suggested, changing the ordering of routes helped, the routes are now:

 routes.MapHttpRoute(
            name: "ActionApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

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

I had to remove action = "" from the ActionApi route otherwise the standard Get on the other controllers stopped working (ie api/values)

api/test/active is now resolving, but I now get a 500 Internal Server Error for /api/test is it possile to have both resolves, so api/test would return "all" and /test/active only return "some"?

It is probably getting confused since you have two methods named action. Try deleting or renaming one of them and see if that works.

One way to do it is to provide a default value for the parameter,

[HttpGet]
public String Active(int id = 0)
{
    var result = new List<string> { "active1", "active2" };

    if (id == 0) {
      return result;
    } else {
      return result[id];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM