我正在使用新的.NET Web API设置休息服务,我遇到了一个小问题.我们希望有一个不同的路由,但我不知道如何实现这一点.
- public class FormController : ApiController
- {
- // api/form
- public string Get()
- {
- return "OK-Get";
- }
- // api/form/method1
- public string Method1()
- {
- return "OK1";
- }
- // api/form/method2
- public string Method2()
- {
- return "OK2";
- }
- }
但这不起作用.如果我转到/ api / form / method2,我会得到OK-Get作为回复.
我认为这与路由有关,但我不确定,因为我之前没有使用过MVC.我已经尝试在WebApiConfig.cs中设置它:
- config.Routes.MapHttpRoute(
- name: "FormApi",routeTemplate: "api/form/{action}"
- );
但那没有做任何事.
解决方法
路由几乎是正确的但主要问题是您在其他操作方法上缺少必需的HttpMethod属性. [HttpGet]是因为它的名字而在第一种方法上推断出来的.这就是你需要的:
- public class FormController : ApiController
- {
- // api/form
- public string Get()
- {
- return "OK-Get";
- }
- // api/form/method1
- [HttpGet]
- public string Method1()
- {
- return "OK1";
- }
- // api/form/method2
- [HttpGet]
- public string Method2()
- {
- return "OK2";
- }
- }
使用属于App_Start / RouteConfig.cs的路由映射
- routes.MapHttpRoute(
- name: "FormApi",routeTemplate: "api/form/{action}",defaults: new { controller = "form",action = "Get"}
- );
有关更多信息,请阅读http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection