ASP.NET Core WebAPI 模式下直接返回 JSON 字符串和使用 Content 返回字符串之间的差别?

yufei       2 年, 5 月 前       1499

ASP.NET Core WebAPI 模式下直接返回 JSON 字符串和使用 Content 返回字符串之间有差别吗?

比如

1. 直接返回 JSON 字符串

/// <summary>
/// 前端不能直接点出来
/// </summary>
/// <returns></returns>
[HttpGet]
public string GetUserById1()
{
    var myData = new
    {
        status = "ok",
        goods = new UserInfor()
        {
            userName = "apple",
            pwd = "12345"
        }
    };
    var jsonData = JsonConvert.SerializeObject(myData);
    return jsonData;
}

2. 使用 Content

/// <summary>
/// 前端可以直接 点出来
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult GetUserById2()
{
    var myData = new
    {
        status = "ok",
        goods = new UserInfor()
        {
            userName = "apple",
            pwd = "12345"
        }
    };
    var jsonData = JsonConvert.SerializeObject(myData);
    return Content(jsonData, "application/json");
}
  1. 大部分情况下,比如我们不关心返回的内容类型 Content-Type 下,那么看起来也没啥差别。
  2. 如果我们关心 Content-Type 那么就有差别了,#2 返回的 Content-Type 是 application/json#1 返回的则是 text/plain.
  3. 因为 Content-Type 的差别,导致我们使用 jQuery 的时候,也是有差别的,#2 success 函数得到的是一个 JavaScript 对象,而 #1 得到的却是字符串。这种差别可以通过传递 datatype:"json" 来消除
$("#rBtn1").click(function () {
    $.ajax({
        url: "https://localhost:8000/api/user/GetUserById1", type: "get", data: { userName: "admin", pwd: "123456" },  success: function (data) {
            console.log(data);
            //不能直接点出来
            console.log(data.status);
        }
    });
    $.ajax({
        url: "https://localhost:8000/api/user/GetUserById1", type: "get", data: { userName: "admin", pwd: "123456" }, dataType: "json", success: function (data) {
            console.log(data);
            //加上dataType: "json",就能直接点出来
            console.log(data.status);
        }
    });
});
$("#rBtn2").click(function () {
    $.ajax({
        url: "https://localhost:8000/api/user/GetUserById2", type: "get", data: { userName: "admin", pwd: "123456" }, success: function (data) {
            console.log(data);
            //能直接点出来
            console.log(data.status);
        }
    });
});
目前尚无回复
简单教程 = 简单教程,简单编程
简单教程 是一个关于技术和学习的地方
现在注册
已注册用户请 登入
关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.