CamiloR CamiloR - 10 days ago 7
AngularJS Question

WebApi Internal Server Error

I have 2 projects, a Front-End (AngularJS) and a Back-End (C# Web-Api). The thing is, when the front-end query the api (e.g GET localhost/api/Especialistas?rol=XXXX) I get a 500 error. Here is the code of the API:

public IHttpActionResult GetEspecialista(string rol)
{
Especialista especialista = db.Especialistas.First( e=> e.Rol == rol);
if (especialista == null)
{
return NotFound();
}
return Ok(especialista);
}


The API is working, since I reach the
return Ok(especialista)
.

The Front-end is using this
Restangular
to query the API

Restangular.one("Especialistas?rol=XXXX").get()


The Network console shows a request
200 OK OPTION
, but a
500 Internal Server Error GET
.

I tried a message handler in the WebApiConfig.cs file to check if the GET request was reaching the Api, and is indeed reaching it, so I don't know what happened, since I didn't change any configuration file.

Any clue on how to fix this problem will be appreciated, thanks.

Answer

If your action is called successfully, but still receive a 500 error, I think the error is created by the serializing of especialista object when converted to a HTTP response.

Most probably, serialization fails because of some navigation properties which creat cycles in your object graph. It is recommended to return simple objects, not entity framework models.

Try the following:

var retObj = new { Prop1 = especialista.Prop1, Prop2 = especialista.Prop2 };
return Ok(retObj);

If above code works, I suggest creating service models "mirror" objects that should be populated based on your data models. These objects should be returned instead of data models.

A good helper to avoid the boilerplate code of property value assignments is Automapper.