我做了一个非常简单的WebApi2
项目仅用于测试目的。我在Dog
中有一个课程Models
:
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();
}
答案 0 :(得分:0)