c# - 如何将多个参数传递/接收到 RESTful Web API GET 方法?

标签 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,因此您可以使用它来获取基于该唯一值的标量值。

但是,如果您想传递多个值(例如字符串和整数)怎么办?是否只是像这样定义一个方法的问题:

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);

?

IOW,路由机制是否会发现,由于传递了两个参数,它应该使用两个参数调用 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 将映射到 GetItemByNameAndIdhttp://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 将映射到 GetItemByIdhttp ://192.112.183.42:80/api/platypusItems/42?name=DuckbilledPlatypisAreGuysToo 将映射到 GetItemByNameAndId 因为 Web API 可以为 GetItemById< 映射 2 个参数而不是 1 个参数.

更多信息可以在 Attribute Routing 上的 Mike Wasson 文章中找到。 , Routing and Action SelectionRouting in Web API .

关于c# - 如何将多个参数传递/接收到 RESTful Web API GET 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19891494/

相关文章:

c# - 调用 C# COM 对象

c# - 文本框两次触发 TextChanged 事件并两次回发,第一次回发状态中止

java - 如何从客户端 Java 调用 PUT 方法?

rest - PATCH 方法是否应该在响应正文中返回资源的所有字段?

asp.net-web-api - YouTube API刷新 token 流程

.net - WebApi OData 实体集/键/导航/键支持

C# NewtonSoft JsonConvert serializexmlnode 到嵌套数组?

c# - 为什么不能在静态方法中使用关键字 'this'?

java - 泽西 Restful 异常(exception) 1

c# - azure 虚拟目录 webdeploy 后 Asp.Net Core WebApi 内部服务器错误