我是 WebAPI 的新手,我不了解 WebAPI v2 中的路由是如何工作的。
我创建了简单的测试 Controller :
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+" });
请您参考如下方法:
下面的代码应该适合你,
[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();
