我正在寻找在我的. net核心Web API控制器中返回带有HTTP状态代码的JSON的正确方法。我以前是这样用的:

public IHttpActionResult GetResourceData()
{
    return this.Content(HttpStatusCode.OK, new { response = "Hello"});
}

这是在一个4.6 MVC应用程序,但现在与。net核心,我似乎没有这个IHttpActionResult,我有ActionResult和使用像这样:

public ActionResult IsAuthenticated()
{
    return Ok(Json("123"));
}

但是服务器的反应很奇怪,如下图所示:

我只是想让Web API控制器返回带有HTTP状态码的JSON,就像我在Web API 2中所做的那样。


当前回答

ASP。NET Core 2.0,从Web API(与MVC统一并使用相同的基类Controller)返回对象的理想方式是

public IActionResult Get()
{
    return new OkObjectResult(new Item { Id = 123, Name = "Hero" });
}

请注意,

它返回200个OK状态码(这是ObjectResult的OK类型) 它进行内容协商,即它将根据请求中的Accept报头返回。如果在请求中发送Accept: application/xml,它将以xml的形式返回。如果不发送任何内容,则默认为JSON。

如果需要发送特定的状态代码,则使用ObjectResult或StatusCode。两者都做同样的事情,并支持内容协商。

return new ObjectResult(new Item { Id = 123, Name = "Hero" }) { StatusCode = 200 };
return StatusCode( 200, new Item { Id = 123, Name = "Hero" });

或者更细粒度的ObjectResult:

 Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection myContentTypes = new Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection { System.Net.Mime.MediaTypeNames.Application.Json };
 String hardCodedJson = "{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";
 return new ObjectResult(hardCodedJson) { StatusCode = 200, ContentTypes = myContentTypes };

如果您特别希望以JSON形式返回,有几种方法

//GET http://example.com/api/test/asjson
[HttpGet("AsJson")]
public JsonResult GetAsJson()
{
    return Json(new Item { Id = 123, Name = "Hero" });
}

//GET http://example.com/api/test/withproduces
[HttpGet("WithProduces")]
[Produces("application/json")]
public Item GetWithProduces()
{
    return new Item { Id = 123, Name = "Hero" };
}

请注意,

两者都以两种不同的方式强制执行JSON。 两者都忽略了内容协商。 第一种方法使用特定的序列化器JSON (object)强制执行JSON。 第二种方法通过使用products()属性(这是一个ResultFilter)和contentType = application/json来实现同样的功能

在官方文档中阅读更多关于它们的信息。点击这里了解过滤器。

示例中使用的简单模型类

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
}

其他回答

我想到的最简单的方法是:

var result = new Item { Id = 123, Name = "Hero" };

return new JsonResult(result)
{
    StatusCode = StatusCodes.Status201Created // Status code here 
};

ASP。NET Core 2.0,从Web API(与MVC统一并使用相同的基类Controller)返回对象的理想方式是

public IActionResult Get()
{
    return new OkObjectResult(new Item { Id = 123, Name = "Hero" });
}

请注意,

它返回200个OK状态码(这是ObjectResult的OK类型) 它进行内容协商,即它将根据请求中的Accept报头返回。如果在请求中发送Accept: application/xml,它将以xml的形式返回。如果不发送任何内容,则默认为JSON。

如果需要发送特定的状态代码,则使用ObjectResult或StatusCode。两者都做同样的事情,并支持内容协商。

return new ObjectResult(new Item { Id = 123, Name = "Hero" }) { StatusCode = 200 };
return StatusCode( 200, new Item { Id = 123, Name = "Hero" });

或者更细粒度的ObjectResult:

 Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection myContentTypes = new Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection { System.Net.Mime.MediaTypeNames.Application.Json };
 String hardCodedJson = "{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";
 return new ObjectResult(hardCodedJson) { StatusCode = 200, ContentTypes = myContentTypes };

如果您特别希望以JSON形式返回,有几种方法

//GET http://example.com/api/test/asjson
[HttpGet("AsJson")]
public JsonResult GetAsJson()
{
    return Json(new Item { Id = 123, Name = "Hero" });
}

//GET http://example.com/api/test/withproduces
[HttpGet("WithProduces")]
[Produces("application/json")]
public Item GetWithProduces()
{
    return new Item { Id = 123, Name = "Hero" };
}

请注意,

两者都以两种不同的方式强制执行JSON。 两者都忽略了内容协商。 第一种方法使用特定的序列化器JSON (object)强制执行JSON。 第二种方法通过使用products()属性(这是一个ResultFilter)和contentType = application/json来实现同样的功能

在官方文档中阅读更多关于它们的信息。点击这里了解过滤器。

示例中使用的简单模型类

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
}

我在我的Asp Net Core Api应用程序中所做的是创建一个从ObjectResult扩展的类,并提供许多构造函数来定制内容和状态代码。 然后我所有的控制器动作都使用适当的构造函数之一。 你可以看看我的实现: https://github.com/melardev/AspNetCoreApiPaginatedCrud

and

https://github.com/melardev/ApiAspCoreEcommerce

下面是类的样子(去我的回购完整代码):

public class StatusCodeAndDtoWrapper : ObjectResult
{



    public StatusCodeAndDtoWrapper(AppResponse dto, int statusCode = 200) : base(dto)
    {
        StatusCode = statusCode;
    }

    private StatusCodeAndDtoWrapper(AppResponse dto, int statusCode, string message) : base(dto)
    {
        StatusCode = statusCode;
        if (dto.FullMessages == null)
            dto.FullMessages = new List<string>(1);
        dto.FullMessages.Add(message);
    }

    private StatusCodeAndDtoWrapper(AppResponse dto, int statusCode, ICollection<string> messages) : base(dto)
    {
        StatusCode = statusCode;
        dto.FullMessages = messages;
    }
}

注意用对象替换dto的基数(dto)应该没问题了。

这是我最简单的解决方案:

public IActionResult InfoTag()
{
    return Ok(new {name = "Fabio", age = 42, gender = "M"});
}

or

public IActionResult InfoTag()
{
    return Json(new {name = "Fabio", age = 42, gender = "M"});
}

我要用这个。我的大问题是我的json是一个字符串(在我的数据库…而不是特定的/已知的类型)。

好吧,我终于把它弄好了。

////[Route("api/[controller]")]
////[ApiController]
////public class MyController: Microsoft.AspNetCore.Mvc.ControllerBase
////{
                    //// public IActionResult MyMethod(string myParam) {

                    string hardCodedJson = "{}";
                    int hardCodedStatusCode = 200;

                    Newtonsoft.Json.Linq.JObject job = Newtonsoft.Json.Linq.JObject.Parse(hardCodedJson);
                    /* "this" comes from your class being a subclass of Microsoft.AspNetCore.Mvc.ControllerBase */
                    Microsoft.AspNetCore.Mvc.ContentResult contRes = this.Content(job.ToString());
                    contRes.StatusCode = hardCodedStatusCode;

                    return contRes;

                    //// } ////end MyMethod
              //// } ////end class

我恰巧用的是asp.net core 3.1

#region Assembly Microsoft.AspNetCore.Mvc.Core, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
//C:\Program Files\dotnet\packs\Microsoft.AspNetCore.App.Ref\3.1.0\ref\netcoreapp3.1\Microsoft.AspNetCore.Mvc.Core.dll

我从这里得到了提示::https://www.jianshu.com/p/7b3e92c42b61