2013-04-24 18 views
1

如何设置路由以支持此操作?如何获得MVC4 Web API以支持同一控制器中的HTTP动词和“动作”方法?

  • GET/API /值/ 工作
  • GET/API /值/ 1 工作
  • POST/API 工作工作
  • PUT/API /值/值
  • DELETE/api /值作品
  • GET/api/values/GetSomeStuff/1 不行!

如果我切换路线,然后GetSomeStuff工作,但然后/ API /值不起作用。我如何配置路线以使它们都起作用?

实例方法:

// 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"; 
    } 

路线都设置这样的:如何

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 } 
     ); 
+0

我用单独的控制器(http://mangoit.wordpress.com/2012/12/ 11/rest-and-rpc-in-asp-net-web-api /) – 2013-04-24 15:31:51

回答

0

你可以尝试以下途径:

 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}" 
     ); 

,改变你的操作方法:

[HttpGet] 
    public string GetSomeStuff(int id2) 
    { 
     return "stuff"; 
    } 
+0

是的,我们确实通过路线限制解决了这个问题,例如您在答案中提到的内容。谢谢。 – Shane 2013-04-25 20:36:17

0

约来代替:

GET /api/values/GetSomeStuff/1 

你设计你的URL这样的:

GET /api/someStuff/1 

现在您可以简单地使用SomeStuffControllerGet(int id)操作。

+2

是唯一的方法是为每个这些单独的控制器?每个控制器是否应该只有5种方法才能成为真正的RESTful? – Shane 2013-04-24 14:29:21

+0

面对类似的问题......这是正确的,一个控制器只有5个方法? – BlueChippy 2013-11-14 07:28:42

相关问题