Recovery Recovery - 1 month ago 21
C# Question

Api lost lost param

Hi I have this code to run my api method

export class MessageService {

constructor(private http: Http) {

}

addMessage(textToSend: string) {
return this.http.post("/api/SendMessage", textToSend); //<- Everytime i have some text in textToSend and this is ok
}
}


And after in my Api my param is equals to null

[HttpPost]
[Route("/api/SendMessage")]
public void SendMessage(string msg) //null value
{
//some code
}

Answer

Possible solution 1:

addMessage(textToSend: string) {
    let body = JSON.stringify({ textToSend });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post("/api/SendMessage/", body, options);
}

// Server side -1
[HttpPost]
[Route("/api/SendMessage")]
public void SendMessage([FromBody]IDictionary<string, string> msg)
{
    var textToSend = msg["textToSend"];
}

// Or create a model and use it

//Server side -2
public class Model
{
    public string textToSend { get; set; }
}
public void SendMessage([FromBody]Model model)

Possible solution 2:

addMessage(textToSend: string) {
    return this.http.post("/api/SendMessage/" + textToSend);
}

[HttpPost]
[Route("/api/SendMessage/textToSend")]
public void SendMessage(string textToSend)
{
    //some code
}
Comments