MVC 4.5的Web API路由不工作? [英] MVC 4.5 Web API Routing not working?
问题描述
第1路线的作品。
例如。 API /架/ SpaceTypes / 1
第二航线不起作用。我得到的多个动作的错误。
例如 API /架/ 1
Q)为什么?
这是我的路线:
config.Routes.MapHttpRoute(
DefaultApiWithAction
API / {控制器} / {行动} / {ID}
);config.Routes.MapHttpRoute(
DefaultApiWithId
API / {}控制器/(编号),
空值,
新{ID = @\\ D +}
);
这是我的控制器:
公开的Htt presponseMessage获取(INT ID)
{
...
}[ActionName(SpaceTypes)]
公众的Htt presponseMessage GetSpaceTypes(INT ID)
{
...
}
对于MVC 4.5,这是唯一可行的事情
目前这个一个错误。
为了让你的路由来工作,所以下面的工作
API /架/ //获取所有货架
API / SpaceTypes / 1 //获取ID 1货架
API /架/ 1 / SpaceTypes / //获取所有的空间类型货架1
您需要做到以下几点。
修改路由到。 (注意:默认操作。)
config.Routes.MapHttpRoute(
名称:DefaultAPi
routeTemplate:API / {控制器} / {ID} / {}行动,
默认:新{ID = RouteParameter.Optional,
行动=DEFAULTACTION
);
在你的控制器更改到基本方法
[ActionName(DEFAULTACTION)]
公共字符串获得()
{
}[ActionName(DEFAULTACTION)]
公共字符串GET(INT ID)
{
}[ActionName(SpaceTypes)]
公共字符串GetSpaceTypes(INT ID)
{
}
现在一切都应该按预期工作。
由于硖Streithorst满了整整此,解释
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)
{
...
}
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
这篇关于MVC 4.5的Web API路由不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!