如何从web.api返回使用json返回mvc控制器的值?
来自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);
答案 0 :(得分:0)
您必须修改发布和阅读回复的方式。
从
修改帖子调用var sucSender = await cl.PostAsJsonAsync("api/sender/successtested", json);
到
var sucSender = await cl.PostAsJsonAsync("api/sender/successtested", json).ConfigureAwait(false);
并修改响应读取调用
var newvar = JsonConvert.DeserializeObject<Tested>(sucSender.ToString());
要
var newvar = await sucSender.Content.ReadAsAsync<Tested>();
这是基于我自己的测试样本的完整代码。我在http://localhost/MyTestTwo托管了一个test2 api控制器,它使用HttpClient在http://localhost/MyTestApi内部调用另一个api。为了简单起见,我保留了Test2Controller Get方法同步,而不是将其转换为异步等待模式。两个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;
}
}
}
有关详细信息,请参阅此帖子Get response from PostAsJsonAsync和HttpClient.GetAsync(...) never returns when using await/async。