Create OData-based Web API - Knowledge Builder API, Part IV: Write Controller

Based on an article entitled " Creating an OData-based API Web - Knowledge Builder API, Part III: the Write Model and the Controller ", the newly created OData Service has been able to properly display metadata and read all the records, but the most basic create, read a single , modify a single function yet.

 

Benpian on the basis of an on enhancing Controller so that it can cover all of the CRUD functions.

 

1. For Create operation is typically mapped to the POST method, the following method is added in the KnowledgesController

        // POST: /Knowledges
        /// <summary>
        /// Support for creating knowledge
        /// </summary>
        public async Task<IActionResult> Post([FromBody] Knowledge knowledge)
        {
            if (!ModelState.IsValid)
            {
                foreach (var value in ModelState.Values)
                {
                    foreach(var err in value.Errors) 
                    {
                        System.Diagnostics.Debug.WriteLine(err.Exception?.Message);
                    }
                }

                return BadRequest();
            }

            _context.Knowledges.Add(knowledge);
            await _context.SaveChangesAsync();

            return Created(knowledge);
        }

Note that since the creation Knowledge must ensure that the integrity of the data (Model used Annotation), so there need to judge ModelState.

In the Debug context, the program will output any error messages.

 

2. For the Update operation, corresponding to the PUT method, the following method is added,

        // PUT: /Knowledges/5
        /// <summary>
        /// Support for updating Knowledges
        /// </summary>
        public async Task<IActionResult> Put([FromODataUri] int key, [FromBody] Knowledge update)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (key != update.ID)
            {
                return BadRequest();
            }

            _context.Entry(update).State = EntityState.Modified;
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!_context.Knowledges.Any(p => p.ID == key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(update);
        }

Here it is omitted the same as the Create operation error output.

 

3. For Delete operation, corresponding to the DELETE method is added:

        // DELETE: /Knowledges/5
        /// <summary>
        /// Support for deleting knowledge by key.
        /// </summary>
        public async Task<IActionResult> Delete([FromODataUri] int key)
        {
            var knowledge = await _context.Knowledges.FindAsync(key);
            if (knowledge == null)
            {
                return NotFound();
            }

            _context.Knowledges.Remove(knowledge);
            await _context.SaveChangesAsync();

            return StatusCode(204); // HttpStatusCode.NoContent
        }

 

4. Update Another method, i.e. HTTP PATCH,

        // PATCH: /Knowleges
        /// <summary>
        /// Support for partial updates of knowledges
        /// </summary>
        public async Task<IActionResult> Patch([FromODataUri] int key, [FromBody] Delta<Knowledge> knowledge)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var entity = await _context.Knowledges.FindAsync(key);
            if (entity == null)
            {
                return NotFound();
            }

            knowledge.Patch(entity);

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!_context.Knowledges.Any(p => p.ID == key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(entity);
        }

 

The single read, corresponding to the HTTP GET operation similarly, except that it needs to specify the Key.

        /// GET: /Knowledges(:id)
        /// <summary>
        /// Adds support for getting a knowledge by key, for example:
        /// 
        /// GET /Knowledges(1)
        /// </summary>
        /// <param name="key">The key of the Knowledge required</param>
        /// <returns>The Knowledge</returns>
        [EnableQuery]
        public SingleResult<Knowledge> Get([FromODataUri] int key)
        {
            return SingleResult.Create(_context.Knowledges.Where(p => p.ID == key));
        }

 

 

6. At this point, the Controller has supported CRUD operations, and other operations can open Postman testing.

At the same time, you can see the OData official documentation methods on Query Data using OData powerful data retrieval functions for reading test.

 

Is whom remember.
Alva Chien

2019.11.19

 

Guess you like

Origin www.cnblogs.com/alvachien/p/11887396.html