[英]How do I get MVC4 Web API to support HTTP Verbs and “Action” methods in the same controller?
How do I setup routing to support this? 如何设置路由以支持此功能?
If I switch the routes around, then GetSomeStuff works, but then /api/values does not work. 如果我切换路由,则GetSomeStuff可以工作,但是/ api / values不能工作。 How do I configure route to have them both work?
如何配置路由以使它们都起作用?
Example methods: 示例方法:
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
// GET api/values/5
[HttpGet]
public string GetSomeStuff(int id)
{
return "stuff";
}
Routes are setup like this: 路由设置如下:
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
How about instead of: 而不是:
GET /api/values/GetSomeStuff/1
you designed your urls like that: 您是这样设计网址的:
GET /api/someStuff/1
Now you could simply have a SomeStuffController
and a Get(int id)
action on it. 现在,您可以简单地对其进行
SomeStuffController
和Get(int id)
操作。
You could try the following routes: 您可以尝试以下路线:
config.Routes.MapHttpRoute(
name: "DefaultController",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"^[0-9]*$" }
);
config.Routes.MapHttpRoute(
name: "DefaultController2",
routeTemplate: "api/{controller}/{action}/{id2}"
);
and change your action method to: 并将您的操作方法更改为:
[HttpGet]
public string GetSomeStuff(int id2)
{
return "stuff";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.