【问题标题】:How to configure Web API2 routes with 2 properties using slash instead of questionmark如何使用斜杠而不是问号配置具有 2 个属性的 Web API 2 路由
【发布时间】:2015-05-14 21:29:36
【问题描述】:

我制作了一个非常简单的WebApi2 项目,仅用于测试目的。我在Models 有一堂Dog

public class Dog
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Breed { get; set; }
}

我有DogController。我想要做的是让 HTTP 请求与这个 URL 一起工作 - localhost:555/api/dog/2/breed/pitbull 但到目前为止我所能做的就是让使用 2 个属性成为可能,但像这样: localhost:555/api/dog/2?breed=pitbull。当我尝试第一个选项时,我得到Error 404 - Not Found

这是我的WebApiConfig

    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
             name: "dogroutewithbreed",
             routeTemplate: "api/dogcontroller/{id}/{breed}"
        );

        config.Routes.MapHttpRoute(
            name: "DogRouteWithId",
            routeTemplate: "api/DogController/{id}"
        );

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

在我的DogController 中,我有这两种方法:

    [HttpGet]
    public Dog GetDogById(int id)
    {
        List<Dog> dogs = new List<Dog>();
        dogs.Add(new Dog { Id = 1, Name = "Sharo", Breed = "Ovcharka" });
        dogs.Add(new Dog { Id = 2, Name = "bimba", Breed = "pitbull" });
        dogs.Add(new Dog { Id = 3, Name = "Reksi", Breed = "Koker" });

        return dogs.Where(d => d.Id == id).FirstOrDefault();
    }

    [HttpGet]
    public Dog Breed(int id, string breed)
    {
        List<Dog> dogs = new List<Dog>();
        dogs.Add(new Dog { Id = 1, Name = "Sharo", Breed = "Ovcharka" });
        dogs.Add(new Dog { Id = 2, Name = "bimba", Breed = "pitbull" });
        dogs.Add(new Dog { Id = 3, Name = "Reksi", Breed = "Koker" });

        return dogs.Where(d => d.Id == id && d.Breed == "pitbull")
                   .FirstOrDefault();
    }

【问题讨论】:

  • 试试这个网址:localhost:555/api/dog/2/pitbul

标签: asp.net-web-api2 asp.net-web-api-routing


【解决方案1】:
猜你喜欢
  • 2017-10-23
  • 2015-07-19
  • 2017-03-24
  • 1970-01-01
  • 2013-11-30
  • 2013-11-11
  • 2017-09-19
  • 2014-05-28
  • 2015-03-19
相关资源
最近更新 更多