[英]WebApi Internal Server Error
I have 2 projects, a Front-End (AngularJS) and a Back-End (C# Web-Api). 我有2个项目,一个前端(AngularJS)和一个后端(C#Web-Api)。 The thing is, when the front-end query the api (eg GET localhost/api/Especialistas?rol=XXXX) I get a 500 error.
问题是,当前端查询api(例如GET localhost / api / Especialistas?rol = XXXX)时,出现500错误。 Here is the code of the API:
这是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)
. 自从到达
return Ok(especialista)
以来,API一直在工作。
The Front-end is using this Restangular
to query the API 前端使用此
Restangular
查询API
Restangular.one("Especialistas?rol=XXXX").get()
The Network console shows a request 200 OK OPTION
, but a 500 Internal Server Error GET
. 网络控制台显示请求
200 OK OPTION
,但显示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. 我在WebApiConfig.cs文件中尝试了一个消息处理程序,以检查GET请求是否已到达Api,并且确实已经到达了Api,所以我不知道发生了什么,因为我没有更改任何配置文件。
Any clue on how to fix this problem will be appreciated, thanks. 感谢您提供有关如何解决此问题的任何线索。
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. 如果成功调用了您的操作,但仍然收到500错误,我认为该错误是由
especialista
对象的序列化(转换为HTTP响应时)引起的。
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 . 好帮手避免财产赋值的样板代码是Automapper 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.