Free Code Snippets in C#, Net Framework, Office 365, ASP.Net,WPF, Visual Studio, SQL Server, Antivirus free
#

 

 

 

With API interfaces, clients such as smartphones, desktop programs or IoT devices can exchange data with an Internet server.

Api corresponds to the so-called REST interface on the Internet, where data is exchanged with HttpGet, HttpPut and HttpPost.

 

Example C # Code Asp.Net Core Api.

Update record with API

There must be a method in the API Controller that defines the attribute

[HttpPut("{id}")]

public async Task<IActionResult> PutProject([FromRoute] int id, [FromBody] Project clientApi_Project)

{..}

 

As soon as a client request arrives as HttpPut and contains this structure, this method is called

1) Then it is checked

a) the data are valid (integer min max values, string lengths)

b) Is the ID of the data supplied the same as the address in the path / ID

 

2) Then the matching data record is retrieved from the server context via SqlClient Context. Context is an ADO Sql Server connection.

If the record is found, the server values ​​are overwritten with incoming values ​​of the API data.

3) and finally the data is updated to the server with .SaveChanges ()

       // PUT-Update: api/Projects/5  *UPDADTE Save Recordset

        [HttpPut("{id}")]

        public async Task<IActionResult> PutProject([FromRoute] int id, [FromBody] Project clientApi_Project)

        {

            //------------< PutProject(ID,Project) >------------

            if (!ModelState.IsValid)

            {

                return BadRequest(ModelState);

            }

 

            if (id != clientApi_Project.ID_Project)

            {

                return BadRequest();

            }

 

            //< get recordset from db >

            var serverProject = await _context.tbl_Projects.SingleOrDefaultAsync(m => m.ID_Project == id);

            //</ get recordset from db >

 

            if (serverProject == null)

            {

                return NotFound();

            }

            //< SET Values >

            serverProject.Text = clientApi_Project.Text;

            serverProject.Title = clientApi_Project.Title;

            serverProject.DtEdit = DateTime.Now;

            //</ SET Values >

 

            //-< save >-

            try

            {

                await _context.SaveChangesAsync();

            }

            //< error >

            catch (DbUpdateConcurrencyException)

            {

                if (!ProjectExists(id))

                {

                    return NotFound();

                }

                else

                {

                    throw;

                }

            }

            //</ error >

            //-</ save >-

 

            //< result >

            return Ok();

            //</ result >

            //------------</ PutProject(ID,Project) >------------

        }

 

 

Create New record with API

There must be a method in the API Controller that has the attribute HttpPost

[HttpPost]

public async Task<IActionResult> Create_NewProject([FromBody] Project clientApi_Project)

{..}

 

As soon as a client request arrives as HttpPost and contains this structure, this method is called

1) Then it is checked

a) the data are valid (integer min max values, string lengths)

b) If the ID is zero or 0. Since this is assigned by the server from auto-increment.

 

2) Adapt data.

The incoming data is directly adapted to default settings and corrections before they are passed to the server.

clientApi_Project.DtCreated = DateTime.Now;

 

3) and finally the data record is added to the context and then the context is updated.

_context.tbl_Projects.Add(clientApi_Project);

await _context.SaveChangesAsync();

 

 

// POST-NEW: api/Projects   *CREATE NEW Recordset

        [HttpPost]

        public async Task<IActionResult> Create_NewProject([FromBody] Project clientApi_Project)

        {

            //------------< Create_NewProject(Project) >------------

            //public async Task<IActionResult> PostProject([FromBody] Project project)

            //*NEW Project

            if (!ModelState.IsValid)

            {

                return BadRequest(ModelState);

            }

            //< check ID >

            if (clientApi_Project.ID_Project!=0)

            {

                return BadRequest("ID not null or 0");

            }

            //</ check ID >

 

            //< Correct Data >

            clientApi_Project.DtCreated = DateTime.Now;

            //< Correct Data >

 

            //< add Recordset >

            //*add

            _context.tbl_Projects.Add(clientApi_Project);

            await _context.SaveChangesAsync();

            //</ add Recordset >

 

            //< return >

            return CreatedAtAction("GetProject", new { id = clientApi_Project.ID_Project }, clientApi_Project);

            //</ return >

            //------------</ Create_NewProject(Project) >------------

        }

 

 

To test the data with the Google Chrome Extension passed

 

Thereafter, the result should be retrievable on the SQL Server

 

Complete API code

With SQL Server table tbl_Projects

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using Freiberufler;

using Freiberufler.Models;

 

namespace Freiberufler.Controllers.Api

{

    [Produces("application/json")]

    [Route("api/Projects")]

    public class ProjectsController : Controller

    {

        private readonly app_Database_Context _context;

 

        #region Class

        public ProjectsController(app_Database_Context context)

        {

            _context = context;

        }

        #endregion

 

        #region API

        //--------------------< region: API Methods >--------------------

 

        // GET-all: api/Projects *List all Records

        [HttpGet]

        public IEnumerable<Project> Gettbl_Projects()

        {

            //------------< Gettbl_Projects() >------------

            return _context.tbl_Projects;

            //------------</ Gettbl_Projects() >------------

        }

 

        // GET-1: api/Projects/5 *SELECT 1 Record

        [HttpGet("{id}")]

        public async Task<IActionResult> GetProject([FromRoute] int id)

        {

            //------------< GetProject(ID) >------------

            if (!ModelState.IsValid)

            {

                return BadRequest(ModelState);

            }

 

            //< get recordset from db >

            var project = await _context.tbl_Projects.SingleOrDefaultAsync(m => m.ID_Project == id);

            //</ get recordset from db >

 

            if (project == null)

            {

                return NotFound();

            }

 

            return Ok(project);

            //------------</ GetProject(ID) >------------

        }

 

        // PUT-Update: api/Projects/5  *UPDADTE Save Recordset

        [HttpPut("{id}")]

        public async Task<IActionResult> PutProject([FromRoute] int id, [FromBody] Project clientApi_Project)

        {

            //------------< PutProject(ID,Project) >------------

            if (!ModelState.IsValid)

            {

                return BadRequest(ModelState);

            }

 

            if (id != clientApi_Project.ID_Project)

            {

                return BadRequest();

            }

 

            //< get recordset from db >

            var serverProject = await _context.tbl_Projects.SingleOrDefaultAsync(m => m.ID_Project == id);

            //</ get recordset from db >

 

            if (serverProject == null)

            {

                return NotFound();

            }

            //< SET Values >

            serverProject.Text = clientApi_Project.Text;

            serverProject.Title = clientApi_Project.Title;

            serverProject.DtEdit = DateTime.Now;

            //</ SET Values >

 

            //-< save >-

            try

            {

                await _context.SaveChangesAsync();

            }

            //< error >

            catch (DbUpdateConcurrencyException)

            {

                if (!ProjectExists(id))

                {

                    return NotFound();

                }

                else

                {

                    throw;

                }

            }

            //</ error >

            //-</ save >-

 

 

 

 

            //< result >

            //return NoContent();

            return Ok();

            //</ result >

            //------------</ PutProject(ID,Project) >------------

        }

 

 

        // POST-NEW: api/Projects   *CREATE NEW Recordset

        [HttpPost]

        public async Task<IActionResult> Create_NewProject([FromBody] Project clientApi_Project)

        {

            //------------< Create_NewProject(Project) >------------

            //public async Task<IActionResult> PostProject([FromBody] Project project)

            //*NEW Project

            if (!ModelState.IsValid)

            {

                return BadRequest(ModelState);

            }

            //< check ID >

            if (clientApi_Project.ID_Project!=0)

            {

                return BadRequest("ID not null or 0");

            }

            //</ check ID >

 

            //< Correct Data >

            clientApi_Project.DtCreated = DateTime.Now;

            //< Correct Data >

 

            //< add Recordset >

            //*add

            _context.tbl_Projects.Add(clientApi_Project);

            await _context.SaveChangesAsync();

            //</ add Recordset >

 

            //< return >

            return CreatedAtAction("GetProject", new { id = clientApi_Project.ID_Project }, clientApi_Project);

            //</ return >

            //------------</ Create_NewProject(Project) >------------

        }

 

        // DELETE: api/Projects/5   *DELETE by ID

        [HttpDelete("{id}")]

        public async Task<IActionResult> DeleteProject([FromRoute] int id)

        {

            //------------< DeleteProject(ID) >------------

            if (!ModelState.IsValid)

            {

                return BadRequest(ModelState);

            }

 

            var project = await _context.tbl_Projects.SingleOrDefaultAsync(m => m.ID_Project == id);

            if (project == null)

            {

                return NotFound();

            }

 

            _context.tbl_Projects.Remove(project);

            await _context.SaveChangesAsync();

 

            return Ok(project);

            //------------</ DeleteProject(ID) >------------

        }

 

        //--------------------</ region: API Methods >--------------------

        #endregion / API

 

        #region Sys Methods

        //--------------------< region: Sys Methods >--------------------

        private bool ProjectExists(int id)

        {

            return _context.tbl_Projects.Any(e => e.ID_Project == id);

        }

        //--------------------</ region: Sys Methods >--------------------

        #endregion /Sys Methods

 

    }

}

 

Mobile
API
»
Asp WPF: Web API Read Values from Asp Net Api with HttpClient
»
API: Data Modify and Create with Api Example
»
Problem ASP.Net: ID is increased by 1000

.

Contact for Jobs, Project Requests: raimund.popp@microsoft-programmierer.de