ApiController获取id不起作用

时间:2018-05-08 16:43:51

标签: c# asp.net-web-api asp.net-web-api-routing

我刚开始使用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://localhost:53198/api/Test/1

匹配的HTTP资源

有谁知道我做错了什么?

2 个答案:

答案 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 }
        );
    }
}

参考Attribute Routing in ASP.NET Web API 2

答案 1 :(得分:2)

你可以做任何一次

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