【发布时间】:2021-04-22 14:47:14
【问题描述】:
为什么我不能在这里返回一个错误的请求?在其他示例中,它工作得很好。
[HttpGet("getPrediction/{dateTime}/{filterUnit}/{filterLocation}/{filterContent}")]
public int GetFillLevelForDateTime(string dateTime, bool filterUnit, int unit, bool filterLocation,
double latitude, double longitude, bool filterContent, string containerContent)
{
try
{
bool tempExists = predictionService.CheckIfMessagesExist(unit, latitude, longitude, filterUnit, filterLocation);
if (tempExists)
{
return GetFillLevelPrediction(dateTime, filterUnit, unit, filterLocation, latitude, longitude, filterContent, containerContent);
}
} catch (Exception ex)
{
return BadRequest();
}
}
【问题讨论】:
-
因为它返回的是
BadRequestResult,而不是int。 -
您的返回类型是
int。因此,您必须:(1)更改返回类型,或(2)返回int。 -
在执行代码之前已经检测到错误。请参阅以下内容:docs.microsoft.com/en-us/aspnet/core/web-api/…
-
观察 - 返回错误请求会产生误导。该状态代码旨在传达调用者提供了错误信息,但您将其用于任何异常。当你的代码被破坏时,你应该使用 Bad Request 来解决数据验证问题和 Internal Server Error。
标签: c# asp.net-core .net-core entity-framework-6 .net-5