【问题标题】:IHttpActionResult won't return JSON objectIHttpActionResult 不会返回 JSON 对象
【发布时间】:2018-08-11 15:03:00
【问题描述】:

我正在尝试使用 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 显示:

虽然请求/响应显示:

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

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

【问题讨论】:

  • 你的console.log响应,它给出了什么?
  • 你能调试吗?你能在浏览器开发工具中查看请求/响应吗?
  • @Crowcoder - 添加了屏幕截图。
  • @Striped - 添加了屏幕截图。
  • 尝试console.log(response.json())。

标签: javascript c# json


【解决方案1】:

Fetch 是这样工作的

主体方法

每个访问响应正文的方法都返回一个 Promise 当关联的数据类型准备好时将被解析。

text() - 将响应文本生成为字符串

json() - 产生 JSON.parse(responseText) 的结果

blob() - 产生一个 Blob

arrayBuffer() - 产生一个 ArrayBuffer

formData() - 生成可以转发给另一个请求的 FormData

我认为你需要

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/

【讨论】:

    【解决方案2】:

    您正在发出 GET 请求,但您的控制器方法正在等待 POST 请求。

    【讨论】:

    • 但请求标头显示:Access-Control-Request-Method:POST - 该方法默认为 GET,但我发送的是 POST。
    • 在调试时你的请求是否以你的登录方法结束?
    猜你喜欢
    • 2015-01-25
    • 1970-01-01
    • 2019-05-05
    • 2017-07-18
    • 2017-06-12
    • 2015-05-23
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    相关资源
    最近更新 更多