Жанры книг
Мы в соц.сетях
ParaKnig📚 » Компьютеры и Интернет » Базы данных » Язык программирования C#9 и платформа .NET5 - Троелсен Эндрю
<< На главную

Язык программирования C#9 и платформа .NET5 - Троелсен Эндрю

Читать онлайн Язык программирования C#9 и платформа .NET5 - Троелсен Эндрю

Шрифт:

-
+

Интервал:

-
+

Закладка:

Сделать
1 ... 599 600 601 602 603 604 605 606 607 ... 642
Перейти на страницу:

protected readonly IRepo&lt;T&gt; MainRepo;

protected readonly IAppLogging&lt;TController&gt; Logger;

protected BaseCrudController(IRepo&lt;T&gt; repo, IAppLogging&lt;TController&gt; logger)

{

  MainRepo = repo;

  Logger = logger;

}

Методы GetXXX()

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

/// &lt;summary&gt;

/// Gets all records

/// &lt;/summary&gt;

/// &lt;returns&gt;All records&lt;/returns&gt;

/// &lt;response code=&quot;200&quot;&gt;Returns all items&lt;/response&gt;

[Produces(&quot;application/json&quot;)]

[ProducesResponseType(StatusCodes.Status200OK)]

[SwaggerResponse(200, &quot;The execution was successful&quot;)]

[SwaggerResponse(400, &quot;The request was invalid&quot;)]

[HttpGet]

public ActionResult&lt;IEnumerable&lt;T&gt;&gt; GetAll()

{

  return Ok(MainRepo.GetAllIgnoreQueryFilters());

}

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

/// &lt;summary&gt;

/// Gets a single record

/// &lt;/summary&gt;

/// &lt;param name=&quot;id&quot;&gt;Primary key of the record&lt;/param&gt;

/// &lt;returns&gt;Single record&lt;/returns&gt;

/// &lt;response code=&quot;200&quot;&gt;Found the record&lt;/response&gt;

/// &lt;response code=&quot;204&quot;&gt;No content&lt;/response&gt;

[Produces(&quot;application/json&quot;)]

[ProducesResponseType(StatusCodes.Status200OK)]

[ProducesResponseType(StatusCodes.Status204NoContent)]

[SwaggerResponse(200, &quot;The execution was successful&quot;)]

[SwaggerResponse(204, &quot;No content&quot;)]

[HttpGet(&quot;{id}&quot;)]

public ActionResult&lt;T&gt; GetOne(int id)

(window.adrunTag = window.adrunTag || []).push({v: 1, el: 'adrun-4-390', c: 4, b: 390})

{

  var entity = MainRepo.Find(id);

  if (entity == null)

  {

    return NotFound();

  }

  return Ok(entity);

}

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

Метод UpdateOne()

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

/// &lt;summary&gt;

/// Updates a single record

/// &lt;/summary&gt;

/// &lt;remarks&gt;

/// Sample body:

/// &lt;pre&gt;

/// {

///   &quot;Id&quot;: 1,

///   &quot;TimeStamp&quot;: &quot;AAAAAAAAB+E=&quot;

///   &quot;MakeId&quot;: 1,

///   &quot;Color&quot;: &quot;Black&quot;,

///   &quot;PetName&quot;: &quot;Zippy&quot;,

///   &quot;MakeColor&quot;: &quot;VW (Black)&quot;,

/// }

/// &lt;/pre&gt;

/// &lt;/remarks&gt;

/// &lt;param name=&quot;id&quot;&gt;Primary key of the record to update&lt;/param&gt;

/// &lt;returns&gt;Single record&lt;/returns&gt;

/// &lt;response code=&quot;200&quot;&gt;Found and updated the record&lt;/response&gt;

/// &lt;response code=&quot;400&quot;&gt;Bad request&lt;/response&gt;

[Produces(&quot;application/json&quot;)]

[ProducesResponseType(StatusCodes.Status200OK)]

[ProducesResponseType(StatusCodes.Status400BadRequest)]

[SwaggerResponse(200, &quot;The execution was successful&quot;)]

[SwaggerResponse(400, &quot;The request was invalid&quot;)]

[HttpPut(&quot;{id}&quot;)]

public IActionResult UpdateOne(int id,T entity)

{

  if (id != entity.Id)

  {

    return BadRequest();

  }

1 ... 599 600 601 602 603 604 605 606 607 ... 642
Перейти на страницу:
На этой странице вы можете бесплатно читать книгу Язык программирования C#9 и платформа .NET5 - Троелсен Эндрю бесплатно.
Комментарии
Открыть боковую панель
Комментарии
Лариса
Лариса 11.03.2026 - 20:17
Странно,здесь имя девочки Аграфена,а на других сайтах я прослушала три книги этого цикла с именем Дарвина.Зачем менять имя и путать читателей? Опечатка- не Дарвина,  а  Дарина.
Григорий
Григорий 09.04.2025 - 22:24
Лучшая книга всех времен
Женя
Женя 02.04.2025 - 16:08
Любимая книга