C# 如何向RESTfulWebAPI GET方法传递/接收多个参数?
获取参数(返回标量值而不是数据集)的GET RESTful方法的常见示例如下所示:C# 如何向RESTfulWebAPI GET方法传递/接收多个参数?,c#,rest,asp.net-web-api,asp.net-4.5,asp.net-web-api-routing,C#,Rest,Asp.net Web Api,Asp.net 4.5,Asp.net Web Api Routing,获取参数(返回标量值而不是数据集)的GET RESTful方法的常见示例如下所示: public string Get(int id) { //get and return the value } …其中传递的val通常是一个ID,因此可以使用它基于该唯一值获取标量值 但是,如果要传递多个值,例如字符串和int,该怎么办?这仅仅是定义这样一种方法的问题: public string Get(string someString, int someInt) { //get and
public string Get(int id)
{
//get and return the value
}
…其中传递的val通常是一个ID,因此可以使用它基于该唯一值获取标量值
但是,如果要传递多个值,例如字符串和int,该怎么办?这仅仅是定义这样一种方法的问题:
public string Get(string someString, int someInt)
{
//get and return the value
}
…并这样称呼它:
//const string uri = "http://192.112.183.42:80/api/platypusItems/someString/someInt";, zB:
const string uri = "http://192.112.183.42:80/api/platypusItems/DuckbilledPlatypisAreGuysToo/42";
var webRequest = (HttpWebRequest) WebRequest.Create(uri);
?
那么,路由机制会不会发现,既然传递了两个参数,它就应该用两个参数调用Get()方法(“配置之上的约定”),或者需要做更多的事情来正确地路由事情呢?如果使用Web API 2,然后,您可以使用属性路由来路由请求,如
http://192.112.183.42:80/api/platypusItems/DuckbilledPlatypisAreGuysToo/42
public class ItemsController : ApiController
{
[Route("api/{controller}/{id}")]
public string GetItemById(int id)
{
// Find item here ...
return item.ToString();
}
[Route("api/{controller}/{name}/{id}")]
public string GetItemByNameAndId(string name, int id)
{
// Find item here ...
return item.ToString();
}
}
http://192.112.183.42:80/api/platypusItems/DuckbilledPlatypisAreGuysToo/42
将映射到GetItemByNameAndId
而http://192.112.183.42:80/api/platypusItems/42
将映射到GetItemById
请注意,您需要在如下配置中启用属性路由:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
但一般来说,您应该将参数作为附加参数传递。GET请求尤其容易。这将在Web API 1和2中起作用:
public class ItemsController : ApiController
{
public string GetItemById(int id)
{
// Find item here ...
return item.ToString();
}
public string GetItemByNameAndId(string name, int id)
{
// Find item here ...
return item.ToString();
}
}
假设您有默认映射配置,http://192.112.183.42:80/api/platypusItems/42
将映射到GetItemById
而http://192.112.183.42:80/api/platypusItems/42?name=DuckbilledPlatypisAreGuysToo
将被映射到GetItemByNameAndId
,因为Web API可以为GetItemById
映射2个参数而不是1个参数
更多信息可以在Mike Wasson关于和的文章中找到。如何在没有飞行前错误的情况下执行JQuery AJAX调用?Thanks@Si8请参阅如何启用CORSThank。我能够启用CORS,但添加标题是导致问题的原因。