我刚开始使用ApiController
。我正在尝试发送HTTP GET发送ID,但它无效。
我的ApiController:
[Route("api/Test")]
public class TestController : ApiController
{
private myEntity db = new myEntity();
[HttpGet]
public HttpResponseMessage GetAll()
{
// Get a list of customers
IEnumerable<Customer> customers = db.Customers.ToList();
// Write the list of customers to the response body
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, customers);
return response;
}
[HttpGet]
public HttpResponseMessage GetById(int id)
{
// Get Customer by id
Customer customer = db.Customers.Where(x => x.Id == id).FirstOrDefault();
HttpResponseMessage response;
if (customer == null)
{
response = Request.CreateResponse(HttpStatusCode.NotFound);
return response;
} else
{
response = Request.CreateResponse(HttpStatusCode.OK, customer);
}
return response;
}
当我在浏览器中运行它时,GetAll
方法可以正常工作。但是,当我尝试GetById
时:
http://localhost:53198/api/Test/1
它返回:
未找到与请求URI
匹配的HTTP资源http://localhost:53198/api/Test/1
有谁知道我做错了什么?
答案 0 :(得分:3)
如果使用属性路由,则需要进行一些更改以确保操作路由是不同的,以避免任何路由冲突。
[RoutePrefix("api/Test")]
public class TestController : ApiController {
private myEntity db = new myEntity();
//GET api/Test
[HttpGet]
[Route("")]
public IHttpActionResult GetAll() {
// Get a list of customers
var customers = db.Customers.ToList();
// Write the list of customers to the response body
return OK(customers);
}
//GET api/Test/1
[HttpGet]
[Route("{id:int}")]
public IHttpActionResult GetById(int id) {
// Get Customer by id
Customer customer = db.Customers.Where(x => x.Id == id).FirstOrDefault();
if (customer == null) {
return NotFound();
}
return Ok(customer);
}
}
这假设已启用属性路由
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
答案 1 :(得分:2)
你可以做任何一次
http://localhost:53198/api/Test/GetById/1
(正如DavidG所说)或
http://localhost:53198/api/Test/1 并将您的代码更改为
[HttpGet]
[Route("{id:int}")]
public HttpResponseMessage GetById(int id)