ASP.NET Core 返回带有状态码的 JSON

233

我正在寻找在.NET Core Web API控制器中正确返回带有HTTP状态码的JSON的方法。我曾经这样使用:

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

这是在一个4.6的MVC应用程序中,但现在使用.NET Core时我似乎没有这个IHttpActionResult,我有ActionResult并且像这样使用:

这是在一个4.6的MVC应用程序中,但现在使用.NET Core时我似乎没有这个IHttpActionResult,我有ActionResult并且像这样使用:

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

但是服务器的响应很奇怪,就像下面的图片:

在此输入图片描述

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


1
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Tseng
12个回答

0
请参考下面的代码,您可以使用不同类型的JSON管理多个状态码。
public async Task<HttpResponseMessage> GetAsync()
{
    try
    {
        using (var entities = new DbEntities())
        {
            var resourceModelList = entities.Resources.Select(r=> new ResourceModel{Build Your Resource Model}).ToList();

            if (resourceModelList.Count == 0)
            {
                return this.Request.CreateResponse<string>(HttpStatusCode.NotFound, "No resources found.");
            }

            return this.Request.CreateResponse<List<ResourceModel>>(HttpStatusCode.OK, resourceModelList, "application/json");
        }
    }
    catch (Exception ex)
    {
        return this.Request.CreateResponse<string>(HttpStatusCode.InternalServerError, "Something went wrong.");
    }
}

9
不行。这不好。 - Phillip Copley

0
在我的 Asp Net Core Api 应用程序中,我创建了一个类,该类扩展自 ObjectResult,并提供许多构造函数以自定义内容和状态码。然后,我的所有 Controller 操作都使用适当的构造函数之一。您可以查看我的实现: https://github.com/melardev/AspNetCoreApiPaginatedCrud

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;
    }
}

注意将base(dto)替换为您的对象,然后您就可以开始了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接