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

 

 

Error Description:

When entering new records via an API in ASP.Net Core MVC, it may happen that the ID is not increased by 1 as specified,

but increased by 1000.

 

 

Reason:

It may be that the incoming record has a weighted ID. When sending new records via the HttpPost API interface, the new ID must not be specified or the ID is definitely 0.

With the add method to the context of the SQL Server database, the ID is always assigned automatically with the next higher number.

 

Old:

Original Microsoft API Template

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

        [HttpPost]

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

        {

            if (!ModelState.IsValid)

            {

                return BadRequest(ModelState);

            }

            //Check here ID

 

            _context.tbl_Projects.Add(project);

            await _context.SaveChangesAsync();

 

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

        }

 

If you check the incoming data, you notice that from time to time incorrect ID data is entered. These must be corrected before further actions.

 

Solution:

One has to check the incoming record of Json on the ID. It can sometimes happen that the incoming ID has been assigned with a number or nonzero.

Therefore, you have to check the incoming record before creating a new record.

At least with the check, if the ID = 0 or zero.

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

        [HttpPost]

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

        {

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

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

            //*NEW Project

            if (!ModelState.IsValid)

            {

                return BadRequest(ModelState);

            }

            if (project.ID_Project!=0)

            {

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

            }

 

 

            _context.tbl_Projects.Add(project);

            await _context.SaveChangesAsync();

 

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

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

        }

 

For a simple test of the function you should enter the new API record several times with test clients like Postman.

Mobile
API
»
Json error: A method was called at an unexpected time
»
StatusCode: 405, ReasonPhrase: Method Not Allowed
»
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