有没有办法基于Action方法的重载执行参数类型?即是否可以在控制器中执行以下操作
public class MyController : ApiController
{
public Foo Get(int id) { //whatever }
public Foo Get(string id) { //whatever }
public Foo Get(Guid id) { //whatever }
}
Run Code Online (Sandbox Code Playgroud)
如果是这样,需要对Route表进行哪些更改.
Mar*_*nes 28
标准路由方法不能很好地支持这种情况.
您可能希望使用基于属性的路由,因为这会为您提供更大的灵活性.
具体来看一下您可以按类型路由的路径约束:
// Type constraints
[GET("Int/{x:int}")]
[GET("Guid/{x:guid}")]
Run Code Online (Sandbox Code Playgroud)
任何其他东西都会变成一个黑客......例如
如果你确实尝试使用标准路由,你可能需要通过它的名称路由到正确的操作,然后使用reg ex的约束(例如guid)路由到所需的默认操作.
控制器:
public class MyController : ApiController
{
[ActionName("GetById")]
public Foo Get(int id) { //whatever }
[ActionName("GetByString")]
public Foo Get(string id) { //whatever }
[ActionName("GetByGUID")]
public Foo Get(Guid id) { //whatever }
}
Run Code Online (Sandbox Code Playgroud)
路线:
//Should match /api/My/1
config.Routes.MapHttpRoute(
name: "DefaultDigitApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { action = "GetById" },
constraints: new { id = @"^\d+$" } // id must be digits
);
//Should match /api/My/3ead6bea-4a0a-42ae-a009-853e2243cfa3
config.Routes.MapHttpRoute(
name: "DefaultGuidApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { action = "GetByGUID" },
constraints: new { id = @"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$" } // id must be guid
);
//Should match /api/My/everything else
config.Routes.MapHttpRoute(
name: "DefaultStringApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { action = "GetByString" }
);
Run Code Online (Sandbox Code Playgroud)
更新
如果做一个FromBody,我通常会使用POST(也许使用FromUri代替模型),但是通过添加以下内容可以满足您的要求.
对于控制器
[ActionName("GetAll")]
public string Get([FromBody]MyFooSearch model)
{
if (model != null)
{
//search criteria at api/my
}
//default for api/my
}
//should match /api/my
config.Routes.MapHttpRoute(
name: "DefaultCollection",
routeTemplate: "api/{controller}",
defaults: new { action = "GetAll" }
);
Run Code Online (Sandbox Code Playgroud)
您可以将您的方法编码如下
[Route("api/My/{id:int}")]
public string Get(int id)
{
return "value";
}
[Route("api/My/{name:alpha}")]
public string Get(string name)
{
return name;
}
[Route("api/My/{id:Guid}")]
public string Get(Guid id)
{
return "value";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30036 次 |
| 最近记录: |