Net Core以JSON格式返回HTTP BadRequest

时间:2019-03-20 06:12:43

标签: c# asp.net-core .net-core asp.net-core-mvc asp.net-core-2.0

在MVC Net Core中,如何以JSON格式返回HttpStatusCodeResult?我在下面放置了原始和新的错误代码。我正在尝试将ASP.Net 4.6.2迁移到ASP Core 2。

错误:

Error   CS0246  The type or namespace name 'HttpStatusCodeResult' could not be found (are you missing a using directive or an assembly reference?)  

编码示例:

public class TaxingAgencyReportController : Controller
{ 
 public JsonResult GetReportPath(int? requestID, int? reportFileInformationID)
    {
        if (requestID.GetValueOrDefault() == 0 || reportFileInformationID.GetValueOrDefault() == 0)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);


 public JsonResult GetLetterPath(int? requestID, int? letterFileInformationID)
    {
        if (requestID.GetValueOrDefault() == 0 || letterFileInformationID.GetValueOrDefault() == 0)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

建议的解决方案退货BadRequest无效:

public JsonResult GetLetterPath(int? requestID, int? letterFileInformationID)
{
    if (requestID.GetValueOrDefault() == 0 || letterFileInformationID.GetValueOrDefault() == 0)
        return BadRequest();

新错误代码:

Error CS0029 Cannot implicitly convert type 'Microsoft.AspNetCore.Mvc.BadRequestResult' to' Microsoft.AspNetCore.Mvc.JsonResult'    

资源:

https://www.talkingdotnet.com/return-http-status-code-from-asp-net-core-methods/

下面的注释适用于Net MVC,而非核心 HttpStatusCodeResult namespace not found

2 个答案:

答案 0 :(得分:2)

如果您想返回一个响应类型为application / json的JSON对象,则应将不是字符串的对象传递给BadRequest()。您甚至可以传递一个匿名对象来快速创建JSON对象,如下所示:

return BadRequest(new { message = "Bad Request"});

还请注意,正确的JSON格式为{“ field_name”:“ field_value”}(值的引号是数字,布尔值,空值)。

或者您可以尝试以下操作:

return Json(new { message = "Bad Request" });

答案 1 :(得分:0)

问题在于您的方法返回类型为JsonResult,但是您返回的是BadRequestResult。

这些结果全部继承自IActionResult接口,因此请将您的返回类型更改为IActionResult

public IActionResult GetLetterPath(int? requestID, int? letterFileInformationID)
{
    if (requestID.GetValueOrDefault() == 0 || letterFileInformationID.GetValueOrDefault() == 0)
        return BadRequest();
...