Multiple parameter in HTTP post request not Binding in Asp.net webApi 2.0

242 Views Asked by At

I have created a sample for post multiple params in HTTP Request.But i can't able to assign the value in Web Api Controller. Please check the below code.

.ts

deleteEntry(entryId: number, entryActiveFlag: string): Observable<number> {
        let dataUrl = `http/localhost:8080/Entry/DeleteEntry`;
        let params = { entryId, entryActiveFlag};
        //params.append(entryId);
        //params.append('entryActiveFlag', entryActiveFlag);
        let body = JSON.stringify(params );
        return this.http.post(dataUrl, body)
            .map(res => res.json())
            .catch(this.handleError);
    }

.WebApi

 [HttpPost("DeleteEntry")]
    public  IActionResult DeleteEntry([FromBody]int entryId,string entryActiveFlag)
    {
        return Ok( _service.DeleteEntry(entryId, entryActiveFlag));
    }
2

There are 2 best solutions below

1
On BEST ANSWER

Wrap the input details in one class and provide the class object as parameter to Web API method. In your case you can add below class -

public class EntryDetails
{
  public int EntryId {get;set;}

  public bool EntryActiveFlag

}

And your web method will be

[HttpPost("DeleteEntry")]
    public  IActionResult DeleteEntry(EntryDetails entryDetails)
    {
        return Ok( _service.DeleteEntry(entryDetails.EntryId, entryDetails.EntryActiveFlag));
    }

Accordingly also change the invocation from client method.

0
On

try below code

let body = "entryId=23&entryActiveFlag=true";
let options = {
    headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
};
     return this.http.post(dataUrl, body,options )
                .map(res => res.json())
                .catch(this.handleError);

Or try below code

const formData = new FormData();
formData.append("key","value");
let options = {
    headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
};

 return this.http.post(dataUrl, formData,options )
            .map(res => res.json())
            .catch(this.handleError);