ApiController 获取 ID 不工作

ApiController get with id not working

我刚开始使用 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

它returns:

No HTTP resource was found that matches the request URI http://localhost:53198/api/Test/1

有谁知道我做错了什么吗?

您可以选择

  • http://localhost:53198/api/Test/GetById/1(如 DavidG 所述)

如果使用属性路由,您需要进行一些更改以确保操作路由不同,以避免任何路由冲突。

[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 }
        );
    }
}

引用Attribute Routing in ASP.NET Web API 2