I cannot return ID when entering data via ASP NET Controller POST

Asked

Viewed 31 times

0

I have the code below, and I need the ID returned as soon as I insert the object. If there is already a registered project, it does not do the insertion, but I need to return some data as empty or null, but I cannot define the same variable to save a null value and a value from project because they have different types, so what should I do in this case?

        public ActionResult<Project> Post(Project project)
        {
            var get = _acess.GetProject(project.Id);

            try
            {


                if (get == null)
                {
                    _acess.AddProject(project);
                }
                else
                {
                    get = null;
                }

                return Ok();
            }
            catch (DataException ex)
            {
                return BadRequest(ex.Message);
            }

        }

1 answer

0


To ensure that your webApi is more compliant with the best practices of a Restful application, it is important that you return to status 201 when the item is servant and 200 when there is no error and no need to create the project.

See below how it looks:

public ActionResult<Project> Post(Project project)
{
    var get = _acess.GetProject(project.Id);

    try
    {
        if (get == null)
        {
            _acess.AddProject(project);
            var urlDoNovoProjeto = $"api/projetos/{project.Id}";
            return Created(urlDoNovoProjeto, project);
        }
        else
        {
            return Ok();
        }
    }
    catch (Exception ex)
    {
        return BadRequest(ex.Message);
    }
}

You must replace the variable value urlDoNovoProjeto as your route.

  • I got it, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.