如何让MVC4 Web API在同一个控制器中支持HTTP Verbs和“Action”方法?

时间:2013-04-24 13:57:38

标签: c# rest asp.net-mvc-4 routes

如何设置路由以支持此功能?

  • GET / api / values / 有效
  • GET / api / values / 1 有效
  • POST / api / values 有效
  • PUT / api /值有效
  • DELETE / api / values 有效
  • GET / api / values / GetSomeStuff / 1 不工作!

如果我切换路线,那么GetSomeStuff可以工作,但是/ api / values不起作用。如何配置路由以使它们都工作?

示例方法:

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

2 个答案:

答案 0 :(得分:0)

如何而不是:

GET /api/values/GetSomeStuff/1

你设计了这样的网址:

GET /api/someStuff/1

现在,您可以对其进行SomeStuffControllerGet(int id)操作。

答案 1 :(得分: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";
    }