繁体   English   中英

IHttpActionResult将不返回JSON对象

[英]IHttpActionResult won't return JSON object

我正在尝试使用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显示: 在此处输入图片说明

当请求/响应显示: 在此处输入图片说明

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

在此处输入图片说明

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

像这样获取作品

身体方法

访问响应主体的每种方法都返回一个Promise,当关联的数据类型准备就绪时,该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));

此处的文档: https : //github.github.io/fetch/

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM