Home > OS >  How do i call a Put-method from WEB API in separate project?
How do i call a Put-method from WEB API in separate project?

Time:11-10

I have built a Web API that is connected to a database for persons. I am now trying to call this Web API from a separate MVC-application which is supposed to have full CRUD. So far i have managed to do so with the Get and Post-methods to create a new person and see a list of the persons currently in the database.

When trying to do a similar call for the Put-method, i get the following error: Error

This is how my method UpdatePerson is written in my API-application:


        [HttpPut]
        [Route("{id:guid}")]
        public async Task<IActionResult> UpdatePerson([FromRoute] Guid id, UpdatePersonRequest updatePersonRequest)
        {
            var person = await dbContext.Persons.FindAsync(id);
    
            if (person != null)
            {   
                person.Name = updatePersonRequest.Name;
                person.Email = updatePersonRequest.Email;
                person.Phone = updatePersonRequest.Phone;
                person.Address = updatePersonRequest.Address;
    
                await dbContext.SaveChangesAsync();
    
                return Ok(person);
            }

And this is how i am trying to consume the API in my separate MVC-project:

        [HttpGet]
        public IActionResult Edit()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Edit(PersonViewModel pvm)
        {
            HttpClient client = new();
            StringContent sContent = new StringContent(JsonConvert.SerializeObject(pvm), Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PutAsync("https://localhost:7281/api/Persons/", sContent);

            response.EnsureSuccessStatusCode();

            if (response.IsSuccessStatusCode)
            {
                return RedirectToAction("Get");
            }
            else
            {
                return NotFound();
            }
        }

Everything is working fine when i try to update the database through the API-app so i am not really sure what is wrong with my request. I hope that someone here can spot the issue right away or at least help me out as i am quite a beginner with WEB APIs.

I have mostly tried changing the URL in my MVC-project but the issue remains.

CodePudding user response:

Are you sure you are receiving the request? It seems that your URI is "https://localhost:7281/api/Persons/" and your API is expecting "https://localhost:7281/api/Persons/{id}" -> where {id} should be the guid you need to append the guid in the URI

CodePudding user response:

Looks like the request doesn't receive the correct the correct parameters, because the URI that appears in your picture seems a generic method.

  • Related