IHttpActionResult不会返回JSON对象

问题描述 投票:0回答:2

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

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

enter image description here

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

javascript c# json
2个回答
2
投票

Fetch就是这样的

身体方法

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

text() - 将响应文本生成为String

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));

doc在这里:https://github.github.io/fetch/


-1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.