0
votes

I am trying to send JSON string from angular to asp.net server. I tried two things to get this data from client side.

1st : I have following code from both server and client side. I am sending a json string, and I expected to receive at backend for what I sent. However, I am just getting this server error before even getting the data.

POST "url" 404 (not found) {"Message":"No HTTP resource was found that matches the request URI 'http://localhost:61476/api/testAPI/getData'.","MessageDetail":"No action was found on the controller 'getData' that matches the request."}

2nd : given that everything is same, i just added [FromBody] in my method like below. This doesn't return any server error and I am able to connect from my client side to server. However, I am getting my body message as null . I tried with Postman, but it seems that it works fine with Postman when I send same data.. I am aware that I can create some modelling in server code to match with my json string from client side, but I don't get why this doesn't work without modelling and also why connection fails without [FromBody].

All I need is to get JSON string from my client side. Can anyone please provide me advice on this?

public string getData([FromBody] string body)

angular

  callServer(){
    var json = {"name":"John Doe", "school": "A"};
    let headers = new HttpHeaders();  
    headers.set('Content-Type', 'application/json');

    this.appService.http.post('http://localhost:61476/api/testAPI/getData', 
                              json, 
                              {headers: headers})
      .subscribe(data => {console.log(data), (err) => console.error("Failed! " + err);
      })
  }

server

    namespace test.Controllers
{
    public class testAPIController : ApiController
    {

    //

    [HttpPost]

    public string getData(string body)
    {
        try
        {
            Log.Info(string.Format("data {0}", body));
            return "ok";
        }

        catch (Exception ex)
        {
            Log.Error(ex.Message);
            return "error";
        }
    }
}}
2

2 Answers

0
votes

Controller:

[HttpPost]

public string postData([FromBody]string body)
{
    try
    {
        Log.Info(string.Format("data {0}", body));
        return Json("ok");
    }

    catch (Exception ex)
    {
        Log.Error(ex.Message);
        return "error";
    }
}

Calling the server:

callServer() : Observable<string> {
    var json = {"name":"John Doe", "school": "A"};
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers }); 
    let apiUrl = 'http://localhost:61476/api/testAPI/postData';

    return this.appService.http.post(`${this.apiUrl}`, json, options)
       .map((res: Response) => res.json())
       .catch(this.handleErrorObservable);
  }

private handleErrorObservable(error: Response | any) {
    console.error(error.message || error);
    return Observable.throw(error.message || error);
}

Calling the service:

this._service.callServer()
    .subscribe(
        res => { console.log(res) },
        err => { console.log(err) }
    )

console.log(res/err) will be your response from the POST call. Sorry if misinterpreted your question but your question is a little hard to follow.

0
votes

404 error is "not found". You must decorate your API Class

[Route("api/TestApi/[action]")]
public class testAPIController : ApiController
{

    [HttpPost]
    [HttpPost, ActionName("getData")]
    public string getData([FromBody]string body)
    {}
}