【问题标题】:Clean up REST response in client or on server?清理客户端或服务器上的 REST 响应?
【发布时间】:2017-07-20 13:08:21
【问题描述】:

我正在C# 中创建一个应用程序,调用RESTful 编码的php 服务返回Json 数据。

一切运行良好 - 除了我从服务器获得的一些结果可能包含额外的服务器端信息。

为了传达有关服务器端发生的情况的更多信息,我使用了echo 调用,然后将其添加到我的RESTFul 函数的“返回”之前。

PHP侧面如下:

echo "testing credentials...\r\n";
// returns user in DB table if success, null otherwise...!
$user = User::doLogin($username, $password, $apiCaller);
if ($user == null) {
    echo "login failed...\r\n";
    return null;
}
echo "login success...\r\n";

当密码错误时,我们得到以下输出

testing credentials...
user is... user1
checking pwd......
NULL
login failed...

当方法成功时,我们得到以下响应

testing credentials...
user is... user1
checking pwd......
login success...
NULL

当我使用以下代码在C# 端返回结果时:

 // get message on some url with a previously create HttpClient
 HttpResponseMessage response = await client.GetAsync(url);
 var response = await client.GetAsync(url);
 var res = response.Content.ReadAsStringAsync().Result;
 if (res != null) {
     // this will actually throw an error as the deserialization fails due
     // due to the non-Json parts...
     var result = JsonConvert.DeserializeObject<string>(res);
 }

我收到一个Unexpected character encountered while parsing value: R. Path '', line 1, position 1.,内容如下

  RESTFul server call to function Login for user...
  User found, checking password
  Grant access with status:
  <<----here comes the actual JSON data.... ---------->>

其实并不奇怪 - 问题是建议的方法是什么?

A.echo 输出重定向到服务器端的其他内容(在哪里以及如何确保我在客户端检索信息)?

B. 在反序列化之前清理答案?

【问题讨论】:

  • 如果您的服务器声称返回 JSON,那么它必须返回有效的 JSON,并且只返回有效的 JSON。将附加信息作为 JSON 返回值的一部分嵌入,或者如果您只是将其用于内部调试,请将其写入日志文件,而不是与 API 响应一起返回。
  • @deceze 你是对的,谢谢。那么我可以将 echo 重定向到一个临时变量,然后在某个时候“jsonify”它吗?

标签: php json rest dotnet-httpclient


【解决方案1】:

IMO 在将响应返回给客户端之前清理服务器上的响应。正如@deceze 指出的那样;如果服务器声称内容主体是 json,它应该只是 json。附带说明一下,服务器是否使用 Content-Type 标头进行响应?

【讨论】:

  • 是的,那么服务器应该只在响应正文中使用有效的 json 进行响应。
  • 好吧,结果我的部分代码写入输出,但不知道哪一部分,我完全无法调试它。无论如何,我所做的是将 echo 重定向到变量并且它有效。但是,这仍然是一种肮脏的方法......至于 IMO 清理 - 你能提供一个例子
  • 您能否提供您应用程序的 PHP 部分,我愿意提供帮助; c# 虽然我不知道。
  • 我用 PHP 代码更新了问题...似乎有些进程正在写入方法内容,但我无法隔离哪个部分,如您所见,NULL 打印在不同的地方取决于方法的答案......真的,不知道发生了什么!
猜你喜欢
  • 2014-02-20
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
相关资源
最近更新 更多