MVC 4.5 Web API Routing not working?

前端 未结 5 1138
感情败类
感情败类 2020-12-10 19:32

The 1st route works.

e.g. api/Shelves/SpaceTypes/1

The 2nd route doesn\'t work. I get multiple actions error.

e.g api/Shelves/1<

5条回答
  •  粉色の甜心
    2020-12-10 20:02

    For MVC 4.5 this is the only thing that works

    There is currently a bug about this.

    In order to get your routing to work so the following work

    api/Shelves/ //Get All Shelves
    api/SpaceTypes/1 //Get Shelf of id 1
    api/Shelves/1/SpaceTypes/  //Get all space types for shelf 1
    

    you need to do the following.

    Change your routing over to. (Note the default action..)

    config.Routes.MapHttpRoute(
        name : "DefaultAPi",
        routeTemplate : "api/{controller}/{id}/{action}",
        defaults: new {id= RouteParameter.Optional, 
        action = "DefaultAction"}
    );
    

    In your controller change the base methods over to

    [ActionName("DefaultAction")]
    public string Get()
    {
    }
    
    [ActionName("DefaultAction")]
    public string Get(int id)
    {
    }
    
    [ActionName("SpaceTypes")]
    public string GetSpaceTypes(int id)
    {
    }
    

    Now everything should work as expected..

    Thanks to Kip Streithorst full this, for a full explanation

提交回复
热议问题