我向API发送请求时,我得到了null,但是当我昂首阔步地执行相同的API时,我得到了结果。
下面是我的ASP.NET代码:
HttpClient client = new HttpClient();
var data = new
{
test = "mydata"
};
client.BaseAddress = new Uri("weburl.com");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
using (client)
{
HttpResponseMessage res = await client.PostAsJsonAsync("api/test", data);
if (res.ReasonPhrase == "OK")
{
res.EnsureSuccessStatusCode();
if (res.IsSuccessStatusCode)
{
var resualt = res.Content;
var res2 = await resualt.ReadAsStringAsync();
var json = JsonConvert.DeserializeObject<JsonModelApi>(res2);
if (json.Succeed)
{
return json.Result;
}
else
return null;
}
else
return null;
}
else
return null;
}
HttpResponseMessage res = await client.PostAsJsonAsync("api/test", data);
res输出:
{StatusCode:200,ReasonPhrase:“ OK”,版本:1.1,内容:System.Net.Http.StreamContent,标头: { 有所不同:接受编码 保护:SA 日期:2018年9月2日,星期日,11:20:16 GMT Set-Cookie:__cfduid = dd54b1f82b2eb402e21bae199246157631535887216; expires =星期一,19年9月2日11:20:16 GMT;路径= /; domain = .myweb; HttpOnly X-Powered-By:飓风11 X-Powered-by:ASP.NET 服务器:cloudflare CF-射线:453f961cb483bead-FRA 连接:保持活动状态 内容长度:0 }}
有人可以帮助我吗?
谢谢。
答案 0 :(得分:0)
我用以下代码解决了问题:
client.BaseAddress = new Uri("mywebapi");
client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
在HttpClient中添加了用户代理,我可能会得到内容:
client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0");
答案 1 :(得分:-1)
尝试这可能是它的工作:
var data = await MobileService.Client.InvokeApiAsync<RETURN TYPE, SEND_TYPE>($"api/test",
HttpMethod_TYPE, null);