Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

asp.net mvc 4 - MVC 4.5 Web API Routing not working?

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

Q) Why?

These are my routes:

config.Routes.MapHttpRoute(
    "DefaultApiWithAction",
    "api/{controller}/{action}/{id}"
);

config.Routes.MapHttpRoute(
    "DefaultApiWithId",
    "api/{controller}/{id}",
    null,
    new { id = @"d+" }
);

This is my controller:

public HttpResponseMessage Get(int id)
{
     ...
}

[ActionName("SpaceTypes")]
public HttpResponseMessage GetSpaceTypes(int id)
{
     ...
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...