10

采用参数(返回标量值而不是数据集)的 GET RESTful 方法的常见示例如下所示:

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

?

IOW,路由机制是否会发现,由于传递了两个参数,它应该使用两个参数调用 Get() 方法(“约定优于配置”),还是需要做更多的事情来适当地路由?

4

1 回答 1

19

如果您使用 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将被映射到GetItemByIdwhilehttp://192.112.183.42:80/api/platypusItems/42?name=DuckbilledPlatypisAreGuysToo将被映射到,GetItemByNameAndId因为 Web API 可以映射 2 个参数而不是 1 个参数GetItemById

更多信息可以在 Mike Wasson 关于属性路由路由和动作选择以及Web API 中的路由的文章中找到。

于 2013-11-10T15:53:09.737 回答