1

我可能只是盯着这个太久了,或者我只是误解了 WebAPI 背后的想法,但我正在寻找是否有办法做到这一点,以便路由表响应自定义操作名称。例如,我想要:

// -> /api/student/studentRecord?studentId=1
[HttpGet]
public Student StudentRecord(int studentId){
    //Do Something and return the Student Record
}

// -> /api/student/newStudent?name=john
[HttpPost]
public int NewStudent(String name){
    //Do whatever and return the new id
}

我不确定我在这里缺少什么,或者是否可以完成。我已经在互联网上搜索了一段时间,似乎无法弄清楚。

webAPI 的重点是在每个控制器中只有一个 PUT、POST、GET 等,还是我可以做我想做的事情?

我玩过路由,但我认为我让它变得更糟了!每次我现在尝试调用某些东西时,都会调用相同的方法。

这是我在路由配置文件中的内容:

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
4

2 回答 2

2

您甚至不需要上面链接的“神奇”操作选择器(尽管它听起来确实很酷) - WebApi 允许action在 url 中包含名称(= 控制器方法名称,除非被覆盖)。

因此,在您的示例中:

// -> /api/student/studentRecord?studentId=1
[HttpGet]
public Student StudentRecord(int studentId){}

路由模板如下所示:

routeTemplate: "api/{controller}/{action}"
  • 控制器将解析给学生
  • 对学生记录的操作
  • 我认为您根本不需要将查询字符串参数放在模板中(除非您希望能够将其附加到 url 部分)

阅读此内容以获取更多详细信息: http ://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

于 2013-01-17T21:44:19.990 回答
2

看看这里Magical Web API action selector - HTTP-verb 和 action name dispatching in a single controller

您可以拥有更好的 API 路由,例如:

/api/student/1/studentrecord/2/

于 2013-01-17T21:06:40.333 回答