Web API如何使一个路由具有多个动作

时间:2013-09-26 17:36:06

标签: asp.net-web-api

使用MVC的WebAPI,我有一个我想用于GET和POST的网址。

示例:

GET /person?personId=5
POST /person - the post would contain info about the new person to post, like { firstName: "Bob" }

我的路线:

config.Routes.MapHttpRoute(
  name: "Person-GetAndPost",
  routeTemplate: "person",
  defaults: new { controller = "Person", action = "Get|Post" }
);

在浏览器中访问person?personId=5时,收到错误No action was found on the controller 'Device' that matches the name 'Get|Post'.

以下是我的控制器中的操作:

// with the action name called "Get", MVC Web API should match the verb GET with this action
public MyModels.Person Get(int personId)
{
    return; // return the person
}

// with the action name called "Post", MVC Web API should match the verb POST with this action
public MyModels.Person Post(MyModels.Person person)
{
    return; // return the updated person
}

这甚至可能吗?感谢。

1 个答案:

答案 0 :(得分:0)

不要设置动作:

config.Routes.MapHttpRoute(
  name: "Person-GetAndPost",
  routeTemplate: "person",
  defaults: new { controller = "Person" }
);