【发布时间】: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