ApiController получить с идентификатором не работает - PullRequest
0 голосов
/ 08 мая 2018

Я только начал работать с ApiController. Я пытаюсь сделать 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

Возвращает:

Не найден ресурс HTTP, соответствующий URI запроса http://localhost:53198/api/Test/1

Кто-нибудь знает, что я делаю не так?

Ответы [ 2 ]

0 голосов
/ 08 мая 2018

При использовании атрибутной маршрутизации вам необходимо внести несколько изменений, чтобы убедиться, что маршруты действий различны, чтобы избежать любых конфликтов маршрутов.

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

Ссылка Маршрутизация атрибутов в ASP.NET Web API 2

0 голосов
/ 08 мая 2018

Вы можете сделать либо

  • http://localhost:53198/api/Test/GetById/1 (как упомянул DavidG)

или

...