如何使用JSON返回Web.api的值?
MVC控制器的代码:
try
{
HttpClient cl = new HttpClient();
cl.BaseAddress = new Uri("http://localhost:35936");
cl.DefaultRequestHeaders.Add("ApiUser", "User");
cl.DefaultRequestHeaders.Add("Password", "Password");
cl.DefaultRequestHeaders.Add("MyVar", "1234");
cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string json = JsonConvert.SerializeObject(testedVar);
var sucSender = await cl.PostAsJsonAsync("api/sender/successtested", json);
if (sucSender.IsSuccessStatusCode)
{
var newvar = JsonConvert.DeserializeObject<Tested>(sucSender.ToString());
}
}
web.api的代码:
string forReturn = "222444";
Tested forRetVar = new Tested
{
test = forReturn
};
var test123 = JsonConvert.SerializeObject(forRetVar);
return JsonConvert.SerializeObject(forRetVar);
您必须修改如何发布和阅读响应。
从
修改帖子调用var sucSender = await cl.PostAsJsonAsync("api/sender/successtested", json);
to
var sucSender = await cl.PostAsJsonAsync("api/sender/successtested", json).ConfigureAwait(false);
并修改从此操作的响应读取调用
var newvar = JsonConvert.DeserializeObject<Tested>(sucSender.ToString());
to
var newvar = await sucSender.Content.ReadAsAsync<Tested>();
这是基于我自己的测试样本的完整代码。我有一个位于http://localhost/mytesttwo托管的Test2 API控制器,该控制器使用httpclient在内部称为http://localhost/mytestapi的另一个API。为了使其简单,我一直保持Test2Controller获取方法同步,而不是将其转换为异步等待模式。两个WebAPI应用程序均在IIS中配置为具有匿名身份验证。
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Http;
namespace MyTestTwo.Controllers
{
public class Test2Controller : ApiController
{
public IHttpActionResult Get()
{
var employeesTask = GetEmp();
employeesTask.Wait();
var employees = employeesTask.Result;
return Ok(employees);
}
private async Task<IEnumerable<string>> GetEmp()
{
IEnumerable<string> response = new List<string>();
var cl = new HttpClient();
cl.BaseAddress = new Uri("http://localhost/MyTestApp/");
cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var sucSender = await cl.PostAsJsonAsync("api/MyTest", "test").ConfigureAwait(false);
if (sucSender.IsSuccessStatusCode)
{
response = await sucSender.Content.ReadAsAsync<IEnumerable<string>>();
}
return response;
}
}
}
请参阅此帖子从PostAsjSonAsync和httpclient.getAsync(...)中获取响应。