【发布时间】:2018-05-08 16:43:50
【问题描述】:
我刚开始使用ApiController。我正在尝试发送一个 ID 的 HTTP GET,但它不起作用。
我的 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://localhost:53198/api/Test/1匹配的 HTTP 资源
有谁知道我做错了什么?
【问题讨论】:
-
您的网址不正确:
http://localhost:53198/api/Test/GetById/1
标签: c# asp.net-web-api asp.net-web-api-routing