我刚接触WebAPI,不了解WebAPI v2中路由的工作原理。
我已经创建了简单的测试控制器:
public class TestController : ApiController
{
public List<string> GetAll()
{
return new List<string>();
}
public string Get(int id)
{
return string.Empty;
}
public string GetSmthByParam1(int param)
{
return string.Empty;
}
public string GetSmthByParam2(int param)
{
return string.Empty;
}
public List<string> GetAllByParam(int param)
{
return new List<string>();
}
}我想通过以下方式了解每种方法:
/Api/Test/GetAll
/Api/Test/Get/3
/Api/Test/GetSmthByParam1/1
/Api/Test/GetSmthByParam2/1
/Api/Test/GetAllByParam/1我不知道如何实现它。我在WebApiConfig.cs中将路由更改为:
config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });发布于 2015-05-08 18:17:32
下面的代码应该可以为你工作,
[RoutePrefix("Test")] public class TestController : ApiController { [Route("GetAll")] public List<string> GetAll() { return new List<string>(); } [Route("Get")] public string Get(int id) { return string.Empty; } [Route("GetSmthByParam1/{param}")] public string GetSmthByParam1(int param) { return string.Empty; } [Route("GetSmthByParam2/{param}")] public string GetSmthByParam2(int param) { return string.Empty; } [Route("GetSmthByParam/{param}")] public List<string> GetAllByParam(int param) { return new List<string>(); } }
您的配置应为config.MapHttpAttributeRoutes();
发布于 2015-06-05 05:10:36
在WebApiConfig
公共静态类WebApiConfig {公共静态空寄存器(HttpConfiguration配置){ // Web API路由config.MapHttpAttributeRoutes();config.Routes.MapHttpRoute(名称:"DefaultApi",控制器:“api/{routeTemplate}/{ id }”,默认值:WebApiConfig{id= RouteParameter.Optional } );... }}
返回路由(“api/ HttpGet /Get/{id}”)公有string Get(int id) { return string.Empty;}
这些链接将非常有用:first & second
发布于 2015-05-08 18:03:41
您应该使用路由属性,请参阅此处的文章:http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
https://stackoverflow.com/questions/30121040
复制相似问题