[英]How can I call different GET Methods in the same Controller utilizing different parameters?
I have a Controller that contains two different Get methods. 我有一个包含两个不同的Get方法的Controller。 One takes an
int
value, while the other takes a String
value, like below: 一个采用
int
值,而另一个采用String
值,如下所示:
public class AccountController : ApiController
{
public String GetInfoByString(String sUserInput)
{
return "GetInfoByString received: " + sUserInput;
}
public String GetInfoByInt(int iUserInput)
{
return "GetInfoByInt received: " + iUserInput;
}
}
My RouteConfig.cs is untouched, and is as follows: 我的RouteConfig.cs未受影响,如下:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
My WebApiConfig.cs is also untouched, and is as follows: 我的WebApiConfig.cs也不受影响,如下:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
I'd like to be able to hit the Web API by using a single link like: 我希望能够通过使用以下链接来访问Web API:
// Hit GetInfoByInt
http://localhost:XXXX/api/account/1
// Hit GetInfoByString
http://localhost:XXXX/api/account/abc
I can hit the first case just fine, but whenever I try to hit the second case, I get the following error: 我可以很好地打第一种情况,但每当我尝试击中第二种情况时,我都会收到以下错误:
<Error>
<Message>The request is invalid.</Message>
<MessageDetail>
The parameters dictionary contains a null entry for parameter 'id' of
non-nullable type 'System.Int64' for method 'TestProject.String GetInfoByInt(Int64)' in 'TestProject.Controllers.AccountController'.
An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
</MessageDetail>
</Error>
Is there any way to hit either Get method depending on whether the user provided a String
or an int
? 有没有办法根据用户提供的
String
或int
来命中Get方法? I'm assuming that there'll need to be changes done in either the RouteConfig or WebApiConfig, but I'm not too sure how to approach this. 我假设需要在RouteConfig或WebApiConfig中进行更改,但我不太确定如何处理此问题。 Maybe it's just an easy solution after all?
也许它毕竟只是一个简单的解决方案?
Also, if it matters, I'd like to be able to hit GetInfoByString with a String
that contains both Letters and Numbers like 'ABC123'
or '123ABC'
. 此外,如果重要的话,我希望能够使用包含字母和数字的
String
来点击GetInfoByString,例如'ABC123'
或'123ABC'
。 GetInfoByInt can be something like '123'
GetInfoByInt可以像
'123'
I'd really like to stick to one Controller rather than splitting this up into multiple Controllers if possible. 我真的很想坚持使用一个控制器,而不是在可能的情况下将其拆分为多个控制器。
Thanks in advance for any help. 在此先感谢您的帮助。
Here's one way of doing things if you want to keep the two actions separate: 如果您想要将两个操作分开,这是一种做事方式:
config.Routes.MapHttpRoute("GetAccountInfoByInt", "api/account/{iUserInput}", new { controller = "account", action = "GetInfoByInt" }, new { iUserInput = @"\d+" });
config.Routes.MapHttpRoute("GetAccountInfoByString", "api/account/{sUserInput}", new { controller = "account", action = "GetInfoByString" });
Note that we're planning to make this kind of thing easier in the future by introducing attribute routing in the next version of Web API: 请注意,我们计划通过在下一版本的Web API中引入属性路由来使这种事情变得更容易:
https://aspnetwebstack.codeplex.com/wikipage?title=Attribute%20routing%20in%20Web%20API https://aspnetwebstack.codeplex.com/wikipage?title=Attribute%20routing%20in%20Web%20API
It should already be available if you're willing to use our nightly builds. 如果您愿意使用我们的夜间版本,它应该已经可用。 Then all you'd have to do would be to add a couple attributes:
那么你所要做的就是添加几个属性:
[HttpGet("api/account/{sUserInput}")]
public String GetInfoByString(String sUserInput)
[HttpGet("api/account/{iUserInput:int}")]
public String GetInfoByInt(int iUserInput)
The following code works for me, note the ActionName and HttpGet attributes, also not in config that you need to define action parameter for api. 以下代码适用于我,请注意ActionName和HttpGet属性,也不需要在配置中为api定义操作参数。
public class AccountController : ApiController
{
[HttpGet]
[ActionName("GetInfoByString")]
public String GetInfoByString(String sUserInput)
{
return "GetInfoByString received: " + sUserInput;
}
[HttpGet]
[ActionName("GetInfoByInt")]
public String GetInfoByInt(int iUserInput)
{
return "GetInfoByInt received: " + iUserInput;
}
}
Do the same in Config for Api 在Config for Api中也这样做
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute("DrawWebService",
"api/{controller}/{action}/{value}",
new { value = System.Web.Http.RouteParameter.Optional });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
One way of overcoming this limitation would be to use nullable parameters, eg 克服该限制的一种方法是使用可空参数,例如
public ActionResult GetInfo(string sUserInput, int? iUserInput)
...and qualifying your logic off the non-null value. ...并使您的逻辑符合非空值。
A work around is to use nullable parameters or trying to parse the string to an integer then qualifying. 解决方法是使用可空参数或尝试将字符串解析为整数然后符合条件。
public ActionResult GetInfo(string sUserInput)
{
var result = sUserInput.IsInt
? GetInfoByInt(int.Parse(sUserInput))
: GetInfoByString(sUserInput)
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.