【问题标题】:Is there a way to return both StatusCode and Content in a HttpRequest?有没有办法在 HttpRequest 中同时返回 StatusCode 和 Content?
【发布时间】:2021-04-06 14:08:34
【问题描述】:

我的应用中有一个登录页面,它向 WebAPI 发出请求,当凭据与数据库记录匹配时,该请求应返回 StatusCode Accepted,但我也希望它返回一些有关用户的数据,以便在应用程序中进一步使用,因此我不必在每次需要时都请求它们。有没有办法通过单个 return 语句同时返回 StatusCode 和数据库记录中的某些内容?

返回 StatusCode 的 API 部分如下所示:

reader = checkCredentials.ExecuteReader();
            reader.Read();
            if (reader.HasRows)
            {
                reader.Close();
                return Accepted();
            }
            else
            {
                reader.Close();
                return Unauthorized();
            }

我怎样才能改变它?

【问题讨论】:

    标签: c# http xamarin model-view-controller webapi


    【解决方案1】:
    return new HttpStatusCodeResult(HttpStatusCode.Accepted, "{yourdata}");
    

    Response.StatusCode = HttpStatusCode.Accepted;
    return Content("{yourdata}");
    

    【讨论】:

    • @Wurfv_ 202 表示该请求只是被接受而不执行,在您的情况下它也已执行,因此您应该返回 200 作为成功执行结果。
    • + 我喜欢在状态码位置添加一点 System.Net.HttpStatusCode 枚举以提高可读性
    • 不应该只是没有状态码的正常响应吗?因为总是会返回 200。
    猜你喜欢
    • 2013-11-24
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多