簡體   English   中英

API多種Get方法和路由

[英]API multiple Get methods and routing

我有一個只有Get Methods的控制器

public class DeviceController : ApiController
{
    List<Device> machines = new List<Device>();

    public IEnumerable<Device> GetAllMachines()
    {
        //do something
        return machines;
    }

    [HttpGet]
    public IEnumerable<Device> GetMachineByID(int id)
    {
        //do something
        return machines;
    }

    [HttpGet]
    public IEnumerable<Device> GetMachinesByKey(string key)
    {
        //do something
        return machines;
    }

}

我希望能夠通過URL訪問這些文件並取回數據

../api/{contorller}/GetAllMachines
../api/{contorller}/GetMachineByID/1001
../api/{contorller}/GetMachiesByKey/HP (machines exist)

當我在IE開發人員模式(f12)中運行前兩個時,我讓Json返回顯示所有機器和機器1001。但是,當我運行GetMachinesByKey / HP時,出現404錯誤。

而且我的WebApiConfig看起來像這樣

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "ActionApi",
            routeTemplate: "api/{controller}/{Action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

有人啟發我我做錯了什么嗎?

路由引擎希望綁定到名為id的變量,如路由配置中所定義:

config.Routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{Action}/{id}", //<--- here {id} means bind to parameter named 'id'
    defaults: new { id = RouteParameter.Optional }
);

在您的操作中, GetMachinesByKey(string key)參數被命名為key ,因此框架不會為您連接這些點。

您可以在查詢字符串中傳遞參數,因此使用/api/{contorller}/GetMachiesByKey/?key=HP形式的URL將正確綁定(您可能需要更改路由配置,因為這不會傳遞id參數,當前配置將是預期的)。

另外,我相信您可以使用屬性路由指定動作的路由 這允許您用一個屬性裝飾您的action方法,該屬性告訴框架如何解決路由,例如:

[Route("<controller>/GetMachinesByKey/{key}")]
public IEnumerable<Device> GetMachinesByKey(string key)

使用RoutePrefix和Route屬性。

[RoutePrefix("api/device")]
public class DeviceController : ApiController
{
List<Device> machines = new List<Device>();

[HttpGet]
[Route("Machines")]
public IEnumerable<Device> GetAllMachines()
{
    //do something
    return machines;
}

[HttpGet]
[Route("Machines/{id:int}")]
public IEnumerable<Device> GetMachineByID(int id)
{
    //do something
    return machines;
}

[HttpGet]
[Route("Machines/{key}")]
public IEnumerable<Device> GetMachinesByKey(string key)
{
    //do something
    return machines;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM