【发布时间】:2020-02-12 16:19:33
【问题描述】:
我的网络服务中有一个路由,它接收带有 Json 正文的 POST 请求并返回 Json 格式的简单数组。我正在使用 PostMan 测试路线,它运行良好。但是当我使用 RestSharp 时,它没有得到任何内容(或反序列化情况下的数据)。
这是我的 C# 代码:
public static async Task<string> UpdateProfile(Profile user, string serviceUrl)
{
string bodyraw = JsonConvert.SerializeObject(user)
var client = new RestClient(serviceUrl);
var request = new RestRequest();
request.Method = Method.POST;
request.Parameters.Clear();
request.AddParameter("application/json", bodyraw, ParameterType.RequestBody);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = await client.ExecuteTaskAsync<Profile>(request);
return response.Data.Address;
}
这是配置文件类:
public class Profile
{
public string Name { get; set; }
public string Family { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Address { get; set; }
public string Postal_code { get; set; }
public string Education { get; set; }
public string Gender { get; set; }
public string Age { get; set; }
public string Default_contact { get; set; }
public override string ToString()
{
return string.Concat(Name," " ,Family, " ", Address);
}
}
这是PostMan输出:
{
"Name": "Holma",
"Family": "Kool",
"Email": "dr@gmail.com",
"Mobile": "09063094744",
"Address": "some city- basic av. sq 60",
"Postal_code": "10246666",
"Education": "1",
"Gender": "male",
"Age": "35"
}
而我使用的 PHP 代码是:
function silverum_update_user_profile($request){
$parameters = $request->get_json_params();// this is a WordPress method and works just fine
$name=sanitize_text_field($parameters['name']);
$family=sanitize_text_field($parameters['family']);
$email=sanitize_text_field($parameters['email']);
$mobile=sanitize_text_field($parameters['mobile']);
$address=sanitize_text_field($parameters['address']);
$postal_code=sanitize_text_field($parameters['postal_code']);
$education=sanitize_text_field($parameters['education']);
$gender=sanitize_text_field($parameters['gender']);
$age=sanitize_text_field($parameters['age']);
$extdp = [
"Name"=>$name,
"Family"=>$family,
"Email"=>$email,
"Mobile"=>$mobile,
"Address"=>$address,
"Postal_code"=>$postal_code,
"Education"=>$education,
"Gender"=>$gender,
"Age"=>$age
];
return $extdp;
}
当 PHP 方法返回“参数”时,它 OK,PostMan 和 RestSharp 都可以看到输出内容,但是当方法返回新数组时,只有 PostMan 能够接收返回的对象。我在这个问题上花了几个小时,但没有得到任何结果。请帮忙。
【问题讨论】:
-
最好的方法是使用像 wireshark 或 fiddler 这样的嗅探器。比较好结果和坏结果的第一个请求。使第一个请求的坏结果看起来像好的请求。
-
而不是 request.AddParameter - 尝试使用 request.AddJsonBody(user) 那么你也不需要手动序列化它。
标签: c# php json postman restsharp