繁体   English   中英

如何为webapi配置此路由?

[英]how to configure this route for webapi?

我有一个控制器来获取资源(例如,Employee),它具有两个属性(例如,CategoryId和DepartmentId)。 我需要配置路由以支持以下URL:

~/api/employees/1234 [to get the employee with employeeId=1234]
~/api/employees [to get all the employees]
~/api/employees?departmentid=1 [to get all the employees with departmentId=1]

控制器代码如下所示:

public IEnumerable<Employee> Get()
{
    ....
}

public IEnumerable<Employee> Get(int employeeId, int departmentId = -1, int categoryId = -1)
{
    .....
}

如何为该控制器配置路由?

谢谢

对于任何querystyring参数,路由侧都没有要做:只需将控制器方法parmater与qs参数名称匹配(不区分大小写)。

如果相反,您的方法参数引用了uri段,则方法参数的名称必须与大括号之间的route参数/段匹配

routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "/api/{controller}/{employeeId}",
    defaults: new { id = RouteParameter.Optional }
);

这意味着您需要使用以下方法的控制器

public class EmployeesController : ApiController
{
public IEnumerable<Employee> Get(int employeeId){...} 
}

请记住,除非使用操作,否则在控制器上,每个http动词只能使用一种方法。
换句话说,除非对两个动词都使用显式操作,否则对动词get具有2方法的示例将不起作用。

您是否看过使用属性路由? 现在,我们广泛使用属性路由,以至于我们已经完全摆脱了MapHttpRoute使用的默认/ controller / action类型路由。

相反,我们按如下方式装饰控制器。 首先,我们为控制器创建一个路由前缀,以便我们知道我们需要的基本路由

/// <summary>   A controller for handling products. </summary>
[RoutePrefix("api/purchasing/locations/{locationid}/products")]
public class ProductsController : PurchasingController
{

然后,对于控制器中的每个动作,我们将其装饰如下:

    [Route("", Name = "GetAllProducts")]
    public IHttpActionResult GetAllProducts(int locationid, ODataQueryOptions<FourthPurchasingAPI.Models.Product> queryOptions)
    {
        IList<Product> products = this.GetProducts(locationid);

    [Route("{productid}", Name = "GetProductById")]
    public IHttpActionResult GetProduct(int locationid, string productid)
    {
        Product product = this.GetProductByID(locationid, productid);

因此,对api / purchasing / locations / 1 / products /的调用将解析为名为“ GetAllProducts”的路由,而对api / purchasing / locations / 1 / products / 1的调用将解析为名为“ GetProductById”的路由

然后,您可以在控制器中使用相同的签名创建另一个GetProduct操作,只需适当地设置属性路由即可,例如

    [Route("/department/{departmentId}", Name = "GetAllProductsForDepartment")]
    public IHttpActionResult GetAllProductsWithDeptId(int locationid, int departmentId)
    {
        IList<Product> products = this.GetProducts(locationid, departmentId);

现在,对api / purchasing / locations / 1 / products / department / 1234的调用将解析为名为“ GetAllProductsForDepartment”的路由

我知道该示例使用的是Web Api 2,但请查看此链接以了解Web Api中的属性路由。 它应该完全相同,否则您将返回IHttpActionResult以外的其他内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM