2012-10-29 36 views
0

我是新来的MVC4 ApiControllers,我需要在我与不同的参数集阿比控制器到达象下面这样:如何在具有相同名称但参数不同的API Controller中使用两种方法?

public Models.Response Get(int skip, int take, int pageSize, int page) 
{ 
    //do something 
} 

public Models.Response Get(int skip, int take, int pageSize, int page, PersonSearchModel personSearchModel) 
{ 
    //search with search model 
} 

我做的“PersonSearchModel”属性和我的要求看起来像一个字符串此:(搜索模型的实例是空的)

本地主机:3039/API/personapi /姓= &姓氏= &出生日期= 1/1/0001%2012:00:00%20AM &性别= 0 & PageIndex = 0 & PageSize = 20 &的SortExpression = & TotalItemCount = 0 & TotalPageCount = 0 & &取= 3 &跳过= 0 &页面= 1 &的pageSize = 3

基于我从MVC3知道它应该将网址映射到搜索模式并选择第二个获取,但我得到“在我的萤火虫中找到与请求匹配的多个操作”异常。我该怎么办?谢谢

回答

0

你不能在控制器的MVC中做的一件事是过载一个函数。

对于额外的参数,将其设置为可选项并检查分配给它的默认值。

0

您可以编写一个派生自ActionMethodSelectorAttribute的自定义属性,用于检查请求参数。您需要过度使用IsValidForRequest方法。这可能是一些像

public class RequireRequestValueAttribute : ActionMethodSelectorAttribute 
{ 
    public RequireRequestValueAttribute(valueName) 
    { 
     ValueName = valueName; 
    } 
    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) 
    { 
     return (controllerContext.HttpContext.Request[ValueName] != null); 
     } 
    } 
    public string ValueName { get; private set; } 
} 

(你可以扩展它来检查多个参数)

您使用此属性与方法,这样

public Models.Response Get(int skip, int take, int pageSize, int page) 
{ 
    //do something 
} 

[RequireRequestValue("personSearchModel")] 
public Models.Response Get(int skip, int take, int pageSize, int page, PersonSearchModel personSearchModel) 
{ 
    //search with search model 
} 

这对我的作品有MVC 3和我想它也应该为MVC 4

相关问题