[英]How to have two methods in API Controller with same name but different arguments?
I'm new to ApiControllers in MVC4 and I need to have to Get in my Api Controller with different set of arguments like below: 我是MVC4中的ApiController的新手,我需要使用以下类似的不同参数集进入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
}
I make a string of "PersonSearchModel" properties and my request look like this: (the instance of search model was empty) 我创建了一个字符串“ PersonSearchModel”,并且我的请求看起来像这样:(搜索模型的实例为空)
localhost:3039/api/personapi/?Firstname=&Lastname=&BirthDate=1/1/0001%2012:00:00%20AM&Gender=0&PageIndex=0&PageSize=20&SortExpression=&TotalItemCount=0&TotalPageCount=0&&take=3&skip=0&page=1&pageSize=3
本地主机:3039 / api / personapi /?Firstname =&Lastname =&BirthDate = 1/1/0001%2012:00:00%20AM&Gender = 0&PageIndex = 0&PageSize = 20&SortExpression =&TotalItemCount = 0&TotalPageCount = 0 && take = 3&skip = 0&page = 1&pageSize = 3
based on what I know from MVC3 it's supposed to map the url to search model and choose the second Get but I get the "Multiple actions were found that match the request" Exception in my firebug. 根据我从MVC3中了解到的信息,应该将URL映射到搜索模型并选择第二个Get,但是在萤火虫中出现了“发现多个与请求匹配的动作”异常。 what should I do?
我该怎么办? thanks
谢谢
One thing you cannot do in MVC in the controller is overload a functions. 您不能在控制器的MVC中做的一件事就是重载函数。
For the extra parameter, set it as optional and check for the default value you assign it. 对于额外的参数,请将其设置为可选,并检查您为其分配的默认值。
You could write a custom attribute derived from ActionMethodSelectorAttribute that would check the request parameters. 您可以编写一个从ActionMethodSelectorAttribute派生的自定义属性,该属性将检查请求参数。 You need to oveeride the IsValidForRequest method.
您需要选择IsValidForRequest方法。 It could be something like
可能是这样的
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; }
}
(You could extend it to check for more than one parameter) (您可以扩展它以检查多个参数)
You use this attribute with your methods like this 您可以将这种属性与类似的方法一起使用
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
}
This works for me with MVC 3 and I suppose it also should for MVC 4 这适用于我与MVC 3,我想它也应适用于MVC 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.