简体   繁体   中英

400 Bad Request for PUT calls Asp Net Web Api 2.2

I am trying to update my resource from Angular app, making Web Api call using PUT method. For some reason, all I receive is 400 Bad Request error, even when I try to do the same using Postman.

Therefore I have two questions, first - if the following code is correct, taking into account web.config file, and console output, and second - should I configure my IIS somehow to allow PUT calls? Everything is running on IIS, and so far I've met with blogpost while working on this problem, which mention something like this - I don't really know what should be changed. cause it seems to me that I've removed WebDAV in my web.config.

web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <location path="." inheritInChildApplications="false">
        <system.webServer>
            <modules runAllManagedModulesForAllRequests="true">
                <remove name="WebDAVModule"/>
            </modules>
            <handlers>
                <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
                <remove name="WebDAV" />
            </handlers>
            <aspNetCore processPath=".\AuctorAPI.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout"   />
        </system.webServer>
    </location>
</configuration>

update method in my angular service:

      updateClient(client: any) {

        console.log(client); 
        var obj = JSON.parse(client);



        const headers = new HttpHeaders().set('content-type', 'application/json');

        var body = {
          name: obj['name'],
          surname: obj['surname'],
          phone: obj['phone'],
          email: obj['email'],
          gymEntriesLeft: obj['gymEntriesLeft'], 
          martialArtsEntriesLeft: obj['martialArtsEntriesLeft'] 
        }

        console.log("ID");
        console.log(obj['id']);
        console.log("BODY");
        console.log(JSON.stringify(body));
        return this.http.put<Client>(this.url + obj['id'], JSON.stringify(body), { headers }).pipe(
          catchError(this.errorHandler)
        );
      }

Angular component (calling delete method)

    onFormSubmit()  {

        this.clientService.updateClient( this.clientById).subscribe(() => { 
          this.getClients();
          this.edit = false;
          this.editRowId = null;
        })

      }

Controller method:

    // PUT: api/Clients/5
            [HttpPut("{id}")]
            public async Task<IActionResult> PutClient(int id, Client client)
            {
                if (id != client.Id)
                {
                    return BadRequest();
                }

                _context.Entry(client).State = EntityState.Modified;

                try
                {
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ClientExists(id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }

                return NoContent();
            }

It seems that you simply have to pass the client id to the request body as that's what's being checked in the action:

var body = {
  id: obj['id'],
  name: obj['name'],
  surname: obj['surname'],
  phone: obj['phone'],
  email: obj['email'],
  gymEntriesLeft: obj['gymEntriesLeft'], 
  martialArtsEntriesLeft: obj['martialArtsEntriesLeft'] 
}

Solution has been found. The problem was that in body there was no ID passed to the PUT action, I debugged it in Visual Studio, by sending Postman request. and as it clearly is written in a code - bad request is returned only when passed ID differs from object's ID, Thank you @AndriiLitvinov, I just discovered that when you posted the comment, but your solution was a favour!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM