对于默认的get,post,put和delete方法,我添加了一些getter,其中一些是参数。
public class AController
{
// GET api/A
[HttpGet]
public HttpResponseMessage GetAs() { ... }
// GET api/A/5
[HttpGet]
public HttpResponseMessage GetA(int id) { ... }
// GET api/A/GetThis
[HttpGet]
public HttpResponseMessage GetThis() { ... }
// GET api/A/GetThat
[HttpGet]
public HttpResponseMessage GetThat() { ... }
// GET api/A/GetMoreInfoAbout/5
[HttpGet]
public HttpResponseMessage GetMoreInfoAbout(int id) { ... }
// PUT api/A
[HttpPut]
public HttpResponseMessage PutA(int id, A a) { ... }
// POST api/A
[HttpPost]
public HttpResponseMessage PostA(A a) { ... }
// DELETA api/A
[HttpDelete]
public HttpResponseMessage DeleteA(int id) { ... }
}
我到目前为止所做的是为每个方法指定一个新的路由,因此我的WebApiConfig.cs被炸毁了,并且每个新的控制器和方法越来越不透明。
我尝试了这种更通用的路由:
config.Routes.MapHttpRoute(
name: "ApiById",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"^[0-9]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByActionId",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: null,
constraints: new { id = @"^[0-9]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}",
defaults: null
);
/* Default route */
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
GET api/A
与GetAs()
匹配,POST api/A
与PostA(A a)
匹配?GET api/A/5
相同。答案 0 :(得分:0)
嗯,这不是我实际想要的解决方案,但它仍然比手动为每个控制器添加一堆路由更通用。
它的作用基本上是为每个控制器添加两条路由。这些路由模板涵盖了对api / [ControllerName] / {id}和api / [ControllerName]的请求,并将它们委托给相应的控制器操作。
foreach (Type t in GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyProject.Controllers")) {
if (typeof(ApiController).IsAssignableFrom(t)) { // Make sure that this controller class is deriving from api controller
string controllerName = t.Name.Substring(0, t.Name.LastIndexOf("Controller")); // Remove Controller postfix from name
config.Routes.MapHttpRoute(
name: "ApiGet" + controllerName,
routeTemplate: "api/" + controllerName + "/{id}",
defaults: new { controller = controllerName, action = "Get" + controllerName },
constraints: new { id = @"^[0-9]+$", httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
);
config.Routes.MapHttpRoute(
name: "ApiGet" + controllerName + "s",
routeTemplate: "api/" + controllerName + "/{id}",
defaults: new { controller = controllerName, id = RouteParameter.Optional, action = "Get" + controllerName + "s" },
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
);
}
}
答案 1 :(得分:0)
我相信你可以在这里使用属性路由。请参阅以下链接以获取更多信息: http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2