1

My angular http request body params are not binding to my api. This is my api which Iam trying to bind body directly without using any complex parameter like class.

public async Task<Object> RejectRequest([FromBody] int RequestId, string 
Reason){
}

This is my angular http request:-

 rejectRequest(data): any {
 var body = JSON.stringify(data);
 const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${localStorage.getItem('token')}`
  }),
  responseType: 'text' as 'text'
 };
 return this.http.post('/api/Dashboard/RejectRequest',body, httpOptions)
}

my body request is :-

{
 "requestid":"45",
 "reason":"dfgsdf"
}
4
  • your api method is httpget ... in angular you use httppost Commented Jun 26, 2019 at 4:34
  • how you understood my api is http get? Commented Jun 26, 2019 at 4:43
  • as request body Commented Jun 26, 2019 at 4:45
  • { "requestid":"45", "reason":"dfgsdf" } i have attached json in question. iam getting it binded if iam using models in api as params. but if direclty used primitive params i cant get it binded Commented Jun 26, 2019 at 4:48

1 Answer 1

3

Problem is that, from UI you sending JSON object as body but in API you receiving it as 2 different parameters.

If you are sending parameters using httpParams from ui you can bind it to api using [FromQuery]

So here you can add a new model in API and change your API method as shown below,

public class MyClass
{
     public string RequestId { get; set; }
     public string Reason { get; set; }
}

public async Task<Object> RejectRequest([FromBody]MyClass MyObj){
   //Your code...
}
Sign up to request clarification or add additional context in comments.

8 Comments

I have tested with that and it will work. but since there is only two params that why i didnt added any classes. can u help me on what chnages i need to make on angular for making this work
@AmeerPappay as you mentioned [FromBody] in API, you can't send an object like how you sending from UI. Instead of [FromBody], make it [FromUri] ([FromQuery] if you are using .net core) and send it as parameter from UI instead of body
how can i send this var body = { "requestid":"45", "reason":"dfgsdf" } as multiple param rather than passing that var body
@AmeerPappay are you trying to send it as httpParams ?
No, as request body. if iam using it to sent as body then i must bind it as model in web api? Also if iam using httpparams then i cant bind using [FromUri]? Iam i right now?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.