我正在尝试使用HttpClient从REST API获取数据,但是我遇到了问题。 使用相同的服务,但通过控制台应用程序,一切正常。
在Controller上一切正常,但是在调用HttpHandler的GetAsync(url)方法时,似乎在后台执行了某些操作,但是什么也没有发生。
这是我的服务
public class UserService : IUsersService
{
private const string url = "https://jsonplaceholder.typicode.com/users";
private IHttpHandler httpHandler;
public UserService(IHttpHandler httpHandler)
{
this.httpHandler = httpHandler;
}
public List<User> GetAllUsers()
{
HttpResponseMessage response = httpHandler.Get(url);
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<List<User>>().Result;
}
//Nice to add Logging system that we cannot connect into following URL
return new List<User>();
}
public User GetUserById(int userId)
{
HttpResponseMessage response = httpHandler.Get(
string.Concat(url,"?id=",userId));
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<List<User>>().Result.FirstOrDefault();
}
//Nice to add Logging system that we cannot connect into following URL
return null;
}
}
这是我的控制器(使用WEB API控制器,httpClient无法从REST API获取数据)
public class UsersController : ApiController
{
IUsersService userService;
public UsersController(IUsersService userService)
{
this.userService = userService;
}
public List<User> GetUsers()
{
return userService.GetAllUsers();
}
public User GetUser(int userId)
{
return userService.GetUserById(userId);
}
}
这是我的HttpHandler,当前正在使用HttpClient:
public class HttpHandler : IHttpHandler
{
private HttpClient client = new HttpClient();
public HttpResponseMessage Get(string url)
{
return GetAsync(url).Result;
}
public HttpResponseMessage Post(string url, HttpContent content)
{
return PostAsync(url, content).Result;
}
public async Task<HttpResponseMessage> GetAsync(string url)
{
return await client.GetAsync(url);
}
public async Task<HttpResponseMessage> PostAsync(string url, HttpContent content)
{
return await client.PostAsync(url, content);
}
}
这是我的控制台应用程序,可以正常运行并显示正确的结果:
class Program
{
static void Main(string[] args)
{
HttpHandler handler = new HttpHandler();
UserService service = new UserService(handler);
var users = service.GetAllUsers();
Console.WriteLine(users[0].Email);
Console.ReadKey();
}
}
我真的不知道,可能是个问题。
答案 0 :(得分:0)
在挖掘网络期间,我找到了问题https://stackoverflow.com/a/10369275/5002910
的解决方案在GetAsync方法的HttpHandler类中,我必须返回
return await client.GetAsync(url).ConfigureAwait(continueOnCapturedContext:false);