ASP.NET Web API中的其他URI控制器中的RESTful控制器(嵌套控制器)

时间:2015-05-20 20:31:44

标签: c# asp.net rest asp.net-web-api

我是编写RESTful Web服务的新手,我想使用ASP.NET Web API构建RESTful Web服务,第三方开发人员将使用它来访问我的应用程序数据。

我的控制器旨在响应以下URI:

api/warehouse --> return list of warehouses
api/warehouse/001 --> return warehouse 001
api/Binwarehouse --> return list of bins by  warehouses
api/Binwarehouse/001 --> return list of bins for warehouse 001

但我真正需要做的是让这个uri结构起作用

api/warehouse/001/Binwarehouse --> return a list of  bins for warehouse 001
api/warehouse/001/Binwarehouse/020 --> return bin "020" from warehouse 001

instead
api/Binwarehouse --> return list of bins by  warehouses
api/Binwarehouse/001 --> return list of bins for warehouse 001

如果这是我的代码怎么办呢?

Global.asax中

using System;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Http;

namespace PSWMWrapperApi
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterOpenAuth();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            RouteTable.Routes.MapHttpRoute(name: "ApiClientes", routeTemplate: "api/{controller}/{dni}",
                defaults: new { dni = System.Web.Http.RouteParameter.Optional });
        }     
    }
}

WarehouseController.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace PSWMWrapperApi
{
    public class WarehouseController : ApiController
    {          
        private Warehouse[] MostrarLista()
        {
            DataSet dsTemp = Funciones.ListaAlmacenes(Funciones.String_ConectaStatic, "1", "1", "1");    
            Warehouse[] listaBodegas = null;

            if (dsTemp != null)
            {
                DataTable oDtTemp = dsTemp.Tables[0];
                if (oDtTemp != null)
                {
                    listaBodegas = new Warehouse[oDtTemp.Rows.Count];
                    for (int i = 0; i < oDtTemp.Rows.Count; i++)
                    {
                        DataRow orow =   oDtTemp.Rows[i];
                        listaBodegas[i] = new Warehouse(orow["WarehouseId"].ToString(), orow["WarehouseDscr"].ToString());
                    }
                }
            }
            return listaBodegas;
        }

        // GET api/<controller>
        public IEnumerable<Warehouse> Get()
        {
            return MostrarLista();
           // return listaClientes;
        }

        // GET api/<controller>/44444444K
        public Warehouse Get(String dni)
        {
           return MostrarLista().Where(x => x.WarehouseId == dni).FirstOrDefault();
        }

    }
}

BinWarehouseController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;

namespace PSWMWrapperApi
{
    public class BinWarehouseController : ApiController
    {
        private BinWarehouse[] MostrarLista()
        {

            DataSet dsTemp = Funciones.ListaBinsAlmacenes(Funciones.String_ConectaStatic, "1", "1","","");    // _fun.ListaAlmacenes( );
            BinWarehouse[] listaBodegas = null;

            if (dsTemp != null)
            {
                DataTable oDtTemp = dsTemp.Tables[0];
                if (oDtTemp != null)
                {
                    listaBodegas = new BinWarehouse[oDtTemp.Rows.Count];
                    for (int i = 0; i < oDtTemp.Rows.Count; i++)
                    {
                        DataRow orow = oDtTemp.Rows[i];
                        listaBodegas[i] = new BinWarehouse(orow["WarehouseId"].ToString(), orow["BinId"].ToString(), orow["BinDscr"].ToString());
                    }
                }
            }
            return listaBodegas;
        }

        // GET api/<controller>
        public IEnumerable<BinWarehouse> Get()
        {
            return MostrarLista();
            // return listaClientes;
        }


        // GET api/<controller>/44444444K
        public BinWarehouse[] Get(String dni)
        { 
                return    MostrarLista().Where(x => x.WarehouseId.Trim() == dni).ToArray();
        }
    }
}

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您需要做的是包含支持所需URI的路由配置。考虑到他们将按照他们注册的顺序进行评估,并且将使用第一个匹配的路线。所以你必须首先包括更具体的,然后是最一般的。除了匹配路径结构,您还可以定义参数,然后选择控制器和操作。

您的路线可能如下所示:

config.Routes.MapHttpRoute(
    name: "BinWarehouse",
    routeTemplate: "api/warehouse/{warehouseId}/Binwarehouse/{binId}",
    defaults: new { controller = "BinWarehouse", action = "MostrarLista" }
);

config.Routes.MapHttpRoute(
    name: "BinWarehouse",
    routeTemplate: "api/warehouse/{warehouseId}/Binwarehouse",
    defaults: new { controller = "Warehouse", action = "MostrarLista" }
);

您的行为必须接收路线捕获的参数(路线参数),即

public BinWarehouse[] MostrarLista(int warehouseId, int binId)

public Warehouse[] MostrarLista(int warehouseId)

但是,请注意,您应该了解更多有关路由和Web API的信息,以便以正确的方式执行操作。这是在开始使用这项技术之前你应该做的基本事情。请至少快速阅读此文档:ASP.NET Web API

如果你阅读了文档,特别是那些与路由相关的文档,你会发现你可以选择使用属性路由,以及如何使用它。

答案 1 :(得分:-1)

只需为要返回的每个数据规范创建特定的Get方法,这样就可以根据所需的数据将参数传递给REST服务。

//Current Get() Methods

//Access url would like /BinWarehouse?warehouseNum=001&binNum=020
public IEnumerable<BinWarehouse> Get(string warehouseNum, string binNum){
  //Grab specific data and return it
}