hanushi
hanushi

Reputation: 161

Http failure response for http://localhost:5000/api/users/siteUsers/[object%20Object],[object%20Object],[object%20Object]: 400 Bad Request

I am trying to add a multi-select dropdown in angular 11 and .netcore 3.1 web api. when i submit the dropdown, errors occur like this. "Http failure response for http://localhost:5000/api/users/siteUsers/[object%20Object],[object%20Object],[object%20Object]: 400 Bad Request"

backend

[Route("siteUsers/{id}")]

How can i pass the from frontend the data.

Edit:

Angular service.ts file

  CreateSiteUsersAsync(data: FormData, id: number) {
    return this.http.post(`${this.baseUrl}/${this.basePath}/siteUsers/${id}`, data);
  }

.ts file

async onSubmitHandler() {
    const data = { ...this.userForm.value};

    await this.userService.CreateSiteUsersAsync(data,data.siteCode).toPromise();
}

Upvotes: 0

Views: 800

Answers (1)

CorrieJanse
CorrieJanse

Reputation: 2598

A few things that is wrong with your function.

First Route is being specified, but the not the Http method. Meaning the default method is Get. You cannot pass form data to a Get method. It should be, Postor Put. So first thing is add a http method:

[Route("siteUsers/{id}")]
[HttpPost]

or more elegantly:

[HttpPost("siteUsers/{id}")]

Next is the receival attributes where you get the data from. There are four options [FromRoute], [FromForm], [FromQuery] and [FromBody].

By default C# uses [FromQuery]. So for both the id and the data you will need to specify where you search this data. See code below:

[HttpPost("siteUsers/{id}")]
public IActionResult MyEndpoint([FromRoute] id, [FromForm] data)
{
    ...
    
    return Ok();
}

You can also use [FromBody] instead of the [FromForm] tag since technically both are are from the body.

Upvotes: 1

Related Questions