protected readonly IRepo MainRepo;

protected readonly IAppLogging Logger;

protected BaseCrudController(IRepo repo, IAppLogging logger)

{

  MainRepo = repo;

  Logger = logger;

}

<p id="AutBody_Root1423"><strong>Методы GetXXX</strong></p>

Есть два HTTP-метода GET, GetOne и GetAll. Оба они используют хранилище, переданное контроллеру. Первым делом добавьте метод Getll, который служит в качестве конечной точки для шаблона маршрута контроллера:

///

/// Gets all records

///

/// All records

/// Returns all items

[Produces("application/json")]

[ProducesResponseType(StatusCodes.Status200OK)]

[SwaggerResponse(200, "The execution was successful")]

[SwaggerResponse(400, "The request was invalid")]

[HttpGet]

public ActionResult> GetAll

{

  return Ok(MainRepo.GetAllIgnoreQueryFilters);

}

Следующий метод получает одиночную запись на основе параметра id, который передается как обязательный параметр маршрута и добавляется к маршруту производного контроллера:

///

/// Gets a single record

///

/// Primary key of the record

/// Single record

/// Found the record

/// No content

[Produces("application/json")]

[ProducesResponseType(StatusCodes.Status200OK)]

[ProducesResponseType(StatusCodes.Status204NoContent)]

[SwaggerResponse(200, "The execution was successful")]

[SwaggerResponse(204, "No content")]

[HttpGet("{id}")]

public ActionResult GetOne(int id)

{

  var entity = MainRepo.Find(id);

  if (entity == null)

  {

    return NotFound;

  }

  return Ok(entity);

}

Значение маршрута автоматически присваивается параметру id (неявно из [FromRoute]).

<p id="AutBody_Root1424"><strong>Метод UpdateOne</strong></p>

Обновление записи делается с применением HTTP-метода PUT. Ниже приведен код метода UpdateOne:

///

/// Updates a single record

///

///

/// Sample body:

///

/// {

///   "Id": 1,

///   "TimeStamp": "AAAAAAAAB+E="

///   "MakeId": 1,

///   "Color": "Black",

///   "PetName": "Zippy",

///   "MakeColor": "VW (Black)",

/// }

///

///

/// Primary key of the record to update

/// Single record

/// Found and updated the record

/// Bad request

[Produces("application/json")]

[ProducesResponseType(StatusCodes.Status200OK)]

[ProducesResponseType(StatusCodes.Status400BadRequest)]

[SwaggerResponse(200, "The execution was successful")]

[SwaggerResponse(400, "The request was invalid")]

[HttpPut("{id}")]

public IActionResult UpdateOne(int id,T entity)

{

  if (id != entity.Id)

  {

    return BadRequest;

  }

  try

  {

    MainRepo.Update(entity);

  }

  catch (CustomException ex)

  {

    // Пример специального исключения.

    // Должно обрабатываться более элегантно.

    return BadRequest(ex);

  }

   catch (Exception ex)

  {

    // Должно обрабатываться более элегантно.

    return BadRequest(ex);

  }

  return Ok(entity);

}

Метод начинается с установки маршрута как запроса HttpPut на основе маршрута производного контроллера с обязательным параметром маршрута id. Значение маршрута присваивается параметру id (неявно из [FromRoute]), а сущность (entity) извлекается из тела запроса (неявно из [FromBody]).Также обратите внимание, что проверка достоверности модели отсутствует, поскольку делается автоматически атрибутом ApiController. Если состояние модели укажет на наличие ошибок, тогда клиенту будет возвращен код 400 (Bad Request).

Перейти на страницу:

Похожие книги