javascript - IHttpActionResult 不会返回 JSON 对象

标签 javascript c# json

我正在尝试使用 IHttpActionResult 将 JSON 结果返回给我的客户端。

我的.Net 代码如下所示:

[AllowAnonymous, HttpPost, Route("")]
public IHttpActionResult Login(LoginRequest login)
{
    if (login == null)
        return BadRequest("No Data Provided");

    var loginResponse = CheckUser(login.Username, login.Password);
    if(loginResponse != null)
    {
        return Ok(new
        {
            message = "Login Success",
            token = JwtManager.GenerateToken(login.Username, loginResponse.Roles),
            success = true
        });
    }
    return Ok( new
    {
        message = "Invalid Username/Password",
        success = false
    });
}

但这不起作用,因为我在 JavaScript 获取后似乎从未在响应中看到 JSON:

const fetchData = ( {method="GET", URL, data={}} ) => {
  console.log("Calling FetchData with URL " + URL);

  var header = {       
    'Content-Type': "application/json",          
  }

  // If we have a bearer token, add it to the header.
  if(typeof window.sessionStorage.accessToken != 'undefined')
  {
    header['Authorization'] = 'Bearer ' + window.sessionStorage.accessToken
  }

  var config = {
    method: method,
    headers: header
  };

  // I think this adds the data payload to the body, unless it's a get. Not sure what happens with a get.
  if(method !== "GET") {
    config = Object.assign({}, config, {body: JSON.stringify(data)});
  }

  // Use the browser api, fetch, to make the call.
  return fetch(URL, config)
      .then(response => {
        console.log(response.body);
        return response;
      })
      .catch(function (e) { 
        console.log("An error has occured while calling the API. " + e); 
      });
}

正文中没有可用的 JSON。 如何将结果返回给客户进行解析? response.body 没有 json 对象。

console.log 显示: enter image description here

虽然请求/响应显示: enter image description here

使用 striped 的建议:console.log(response.json())

enter image description here

我看到了那里的消息。似乎是在错误的地方。不是应该在体内吗?

最佳答案

获取的工作方式如下

Body methods

Each of the methods to access the response body returns a Promise that will be resolved when the associated data type is ready.

text() - yields the response text as String

json() - yields the result of JSON.parse(responseText)

blob() - yields a Blob

arrayBuffer() - yields an ArrayBuffer

formData() - yields FormData that can be forwarded to another request

我认为你需要

return fetch(URL, config)
      .then(response => response.json())
      .catch(e => console.log("An error has occured while calling the API. " + e));

文档在这里:https://github.github.io/fetch/

关于javascript - IHttpActionResult 不会返回 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49085367/

相关文章:

c# - 在 Telerik MVC AJAX 绑定(bind)属性列上使用自定义日期格式化程序

javascript - 使用 javascript 在客户端打印 PDF 文件

iphone - 如何格式化从 Web 服务返回的字符串数组

javascript - nodejs - 在另一个 js 文件中调用函数时打印未定义

javascript - 如何自动关闭切换按钮

javascript - 使用 JavaScript 的小数背包

javascript - 无法在 MVC 中捆绑 jQuery 文件

javascript - 将 C# 正则表达式转换为 JavaScript 正则表达式

javascript - "delete"- 恢复 native 函数不适用于已更改的原型(prototype),那怎么办?

javascript - 在 Dropzone 文件上传控件中禁用多选