【问题标题】:How do I return specific string value from webapi?如何从 webapi 返回特定的字符串值?
【发布时间】:2020-10-17 18:19:45
【问题描述】:

我想返回以下 JSON,但我错过了语法。我该如何纠正?

在我的 HomeController.cs 中,

If (result.IsUserActive) return JSON { “UserStatus” : “Active” }

如何在 webapi 的 Get 方法中返回值 “UserStatus” : “Active”

一定是这样的:

[HttpGet]
        
        public IHttpActionResult GetUserStatus(int id)
        {
           
            var result = GetStatus(id);    
            if (result.IsUserActive)
            {
                return json ({ “UserStatus” : “Active” });
            }

【问题讨论】:

    标签: asp.net-web-api asp.net-web-api2


    【解决方案1】:

    您可以像这样简单地返回 Json:

    var result = new {UserStatus="Active" };
    return Ok(result);
    

    【讨论】:

    • if (result.IsUserActive) { var status = new { UserStatus = "Active" };返回确定(状态);此解决方案适用于 Web Api 2。
    • 也可以使用 return Json(status);返回 Json() 始终返回 HTTP 200 和 JSON 格式的结果,无论传入请求的 Accept 标头中的格式是什么。返回 Ok() 将返回 HTTP 200,但结果将根据 Accept 请求标头中指定的内容进行格式化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 2020-11-12
    • 2021-10-23
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    相关资源
    最近更新 更多