所以我很熟悉如何写默认的Get,Post,Put,Delete
//GET api/customer
public string Get(){}
//GET api/customer/id
public string Get(int id){}
//POST api/customer
public void Post([FromBody]string value){}
//PUT api/customer/id
public void Put(int id, [FromBody]string value){}
//DELETE api/customer/id
public void Delete(int id){}
但是,我如何编写添加另一个Get端点w/o,必须创建一个全新的控制器?我想拿客户的元数据?我需要对routeConfig做任何更改吗?如果是这样的话,我怎么做呢?然后如何在javascript中使用新的路由呢?
//GET api/customer/GetMetaData
public string GetMetaData(){
}
发布于 2014-05-30 23:09:41
您可以使用属性Route。此属性是在WebApi 20中添加的,您可以在方法级别使用它来定义新路由或更多路由,您使用它的方式类似于[Route("Url/route1/route1")]
。
使用上面的示例之一,它将如下所示:
//GET api/customer/GetMetaData
[Route("api/customer/GetMetaData")]
public string Get2(){
//your code goes here
}
如果要在类中声明几条路由,那么可以在类级别上使用RoutePrefix属性(如[RoutePrefix("url")]
)。这将为Controller类中的所有方法设置一个新的基本URL。
例如:
[RoutePrefix("api2/some")]
public class SomeController : ApiController
{
// GET api2/some
[Route("")]
public IEnumerable<Some> Get() { ... }
// GET api2/some/5
[Route("{id:int}")]
public Some Get(int id) { ... }
}
注意:在上面的示例中,我展示了一个示例,其中路由允许我们设置类型约束。
https://stackoverflow.com/questions/23964610
复制相似问题