The app I'm working on is supposed to retrieve a json string with the http client after which it gets deserialised and used in the app.
Everything works, except for the await functionality. I'm doing something wrong and I can't seem to figure out what. How can I make sure that my DataService class waits untill I have my json and it has been deserialized?
The DataService class:
class DataService : IDataService
{
private IEnumerable<Concert> _concerts;
public DataService()
{
_concerts = new DataFromAPI()._concerts;
Debug.WriteLine("____Deserialization should be done before continuing____");
**other tasks that need the json**
}
}
My http client class:
class DataFromAPI
{
public IEnumerable<Concert> _concerts { get; set; }
public DataFromAPI()
{
Retrieve();
}
public async Task Retrieve()
{
try
{
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
var result = await client.GetAsync(new Uri("http://url-of-my-api"), HttpCompletionOption.ResponseContentRead);
string jsonstring = await result.Content.ReadAsStringAsync();
DownloadCompleted(jsonstring);
}
catch {}
}
void DownloadCompleted(string response)
{
try
{
_concerts = JsonConvert.DeserializeObject<IEnumerable<Concert>>(response.ToString());
}
catch {}
}
}
solution
After a lot of trial and error I realised that for this particular thingy it didn't have to be async, so I just recreated is on the main thread, with success:
The DataService class:
class DataService : IDataService
{
private IEnumerable<Concert> _concerts;
public DataService()
{
_concerts = new DataFromAPI()._concerts;
}
}
My http client class:
public static class DataFromAPI
{
public void Retrieve()
{
try
{
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
var result = client.GetAsync("http://url-of-my-api").Result;
if (result.IsSuccessStatusCode)
{
var responseContent = result.Content;
}
DownloadCompleted(result.Content.ReadAsStringAsync().Result);
}
catch {}
}
}
You are calling Retrieve() without await in the DataFromAPI constructor, That's why your method isn't awaited.
You should better call this methods outside the constructor, with the await keyword like this :
await Retrieve();
You have to refactor your code a little. Here's an example :
public class DataService : IDataService
{
private IEnumerable<Concert> _concerts;
public async Task LoadData()
{
_concerts = await DataFromAPI.Retrieve();
**other tasks that need the json**
}
}
public static class DataFromAPI
{
public static async Task<IEnumerable<Concert>> Retrieve()
{
try
{
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
var result = await client.GetAsync(new Uri("http://url-of-my-api"), HttpCompletionOption.ResponseContentRead);
string jsonstring = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<IEnumerable<Concert>>(response.ToString());
}
catch(Exception)
{
}
return Enumerable.Empty<Concert>();
}
}
Then, when you create your DataService instance, just after you have to call it's LoadData() method.
DataService ds = new DataService();
await ds.LoadData();
And of course, these two lines of code must also be called from an async method. (async / await all the way)
After a lot of trial and error I realised that for this particular thingy it didn't have to be async, so I just recreated is on the main thread, with success:
The DataService class:
class DataService : IDataService
{
private IEnumerable<Concert> _concerts;
public DataService()
{
_concerts = new DataFromAPI()._concerts;
}
}
My http client class:
public static class DataFromAPI
{
public void Retrieve()
{
try
{
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
var result = client.GetAsync("http://url-of-my-api").Result;
if (result.IsSuccessStatusCode)
{
var responseContent = result.Content;
}
DownloadCompleted(result.Content.ReadAsStringAsync().Result);
}
catch {}
}
}
Related
I am dealing with a piece of code that looks like this:
public class Uploader : IUploader
{
public Uploader()
{
// assign member variables to dependency injected interface implementations
}
public async Task<string> Upload(string url, string data)
{
HttpResponseMessage result;
try
{
var handler = new HttpClientHandler();
var client = new HttpClient(handler);
result = await client.PostAsync(url, new FormUrlEncodedContent(data));
if (result.StatusCode != HttpStatusCode.OK)
{
return "Some Error Message";
}
else
{
return null; // Success!
}
}
catch (Exception ex)
{
// do some fancy stuff here
}
}
}
I am trying to unit test the Upload function. In particular, I need to mock the HttpClient. After reading the other answers on here and these two articles, I know that one of the better ways to solve this is to mock the HttpMessageHandler instead and pass that to HttpClient and have it return whatever I want.
So, I started along that path by first passing in HttpClient in the constructor as a dependency:
public class Uploader : IUploader
{
private readonly HttpClient m_httpClient; // made this a member variable
public Uploader(HttpClient httpClient) // dependency inject this
{
m_httpClient = httpClient;
}
public async Task<string> Upload(string url, string data)
{
HttpResponseMessage result;
try
{
var handler = new HttpClientHandler();
result = await m_httpClient.PostAsync(url, new FormUrlEncodedContent(data));
if (result.StatusCode != HttpStatusCode.OK)
{
return "Some Error Message";
}
else
{
return null; // Success!
}
}
catch (Exception ex)
{
// do some fancy stuff here
}
}
}
and adding: services.AddSingleton<HttpClient>(); to the ConfigureServices method of Startup.cs.
But now I face a slight issue where the original code specifically creates a HttpClientHandler to pass in. How then do I refactor that to take in a mockable handler?
I find the simplest way is to continue using HttpClient, but pass in a mocking HttpClientHandler such as https://github.com/richardszalay/mockhttp
Code sample from the link above:
var mockHttp = new MockHttpMessageHandler();
mockHttp.When("http://localhost/api/user/*")
.Respond("application/json", "{'name' : 'Test McGee'}");
// Inject the handler or client into your application code
var client = mockHttp.ToHttpClient();
var response = await client.GetAsync("http://localhost/api/user/1234");
var json = await response.Content.ReadAsStringAsync();
Console.Write(json); // {'name' : 'Test McGee'}
The Dependency Injection framework built into .NET Core ignores internal constructors, so it will call the parameter-less constructor in this scenario.
public sealed class Uploader : IUploader
{
private readonly HttpClient m_httpClient;
public Uploader() : this(new HttpClientHandler())
{
}
internal Uploader(HttpClientHandler handler)
{
m_httpClient = new HttpClient(handler);
}
// regular methods
}
In your unit tests, you can use the constructor accepting the HttpClientHandler:
[Fact]
public async Task ShouldDoSomethingAsync()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.When("http://myserver.com/upload")
.Respond("application/json", "{'status' : 'Success'}");
var uploader = new Uploader(mockHttp);
var result = await uploader.UploadAsync();
Assert.Equal("Success", result.Status);
}
Normally I'm not a big fan of having an internal constructor to facilitate testing, however, I find this more obvious and self-contained than registering a shared HttpClient.
HttpClientFactory might be another good option, but I haven't played around with that too much, so I'll just give info on what I've found useful myself.
One way would be to abstract your HTTP functionality into a service i.e. HttpService which implements an interface of IHttpService:
IHttpService
public interface IHttpService
{
Task<HttpResponseMessage> Post(Uri url, string payload, Dictionary<string, string> headers = null);
}
HttpService
public class HttpService : IHttpService
{
private static HttpClient _httpClient;
private const string MimeTypeApplicationJson = "application/json";
public HttpService()
{
_httpClient = new HttpClient();
}
private static async Task<HttpResponseMessage> HttpSendAsync(HttpMethod method, Uri url, string payload,
Dictionary<string, string> headers = null)
{
var request = new HttpRequestMessage(method, url);
request.Headers.Add("Accept", MimeTypeApplicationJson);
if (headers != null)
{
foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}
}
if (!string.IsNullOrWhiteSpace(payload))
request.Content = new StringContent(payload, Encoding.UTF8, MimeTypeApplicationJson);
return await _httpClient.SendAsync(request);
}
public async Task<HttpResponseMessage> Post(Uri url, string payload, Dictionary<string, string> headers = null)
{
return await HttpSendAsync(HttpMethod.Post, url, payload, headers);
}
}
Add to your services:
services.AddSingleton<IHttpService, HttpService>();
In your class you would then inject IHttpService as a dependency:
public class Uploader : IUploader
{
private readonly IHttpService _httpService; // made this a member variable
public Uploader(IHttpService httpService) // dependency inject this
{
_httpService = httpService;
}
public async Task<string> Upload(string url, string data)
{
HttpResponseMessage result;
try
{
result = await _httpService.PostAsync(new Uri(url), data);
if (result.StatusCode != HttpStatusCode.OK)
{
return "Some Error Message";
}
else
{
return null; // Success!
}
}
catch (Exception ex)
{
// do some fancy stuff here
}
}
}
You could then use Moq to mock HttpService in your unit test:
[TestClass]
public class UploaderTests
{
private Mock<IHttpService> _mockHttpService = new Mock<IHttpService>();
[TestMethod]
public async Task WhenStatusCodeIsNot200Ok_ThenErrorMessageReturned()
{
// arrange
var uploader = new Uploader(_mockHttpService.Object);
var url = "someurl.co.uk";
var data = "data";
// need to setup your mock to return the response you want to test
_mockHttpService
.Setup(s => s.PostAsync(url, data))
.ReturnsAsync(new HttpResponseMessage(HttpStatusCode.InternalServerError));
// act
var result = await uploader.Upload(new Uri(url), data);
// assert
Assert.AreEqual("Some Error Message", result);
}
[TestMethod]
public async Task WhenStatusCodeIs200Ok_ThenNullReturned()
{
// arrange
var uploader = new Uploader(_mockHttpService.Object);
var url = "someurl.co.uk";
var data = "data";
// need to setup your mock to return the response you want to test
_mockHttpService
.Setup(s => s.PostAsync(new Uri(url), data))
.ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK));
// act
var result = await uploader.Upload(url, data);
// assert
Assert.AreEqual(null, result);
}
}
I want to try and refactor this method a bit better while I am having some difficulty in understand the async I have a web api2 project which I use my data access layer to share to a phone app. I am not sure if I have the syntax correct I am using a xamrian shared library here in a xamrian forms app.
I will have various methods link get clients which will have the end point API/clients but obv their return type would be different.
How would one make the below work well with a list view say.
How would I consume the below method as well , what is general practise to then store the jobs locally in sql lite.
public string BaseUrl { get; set; }
public string EndPoint { get; set; }
Lets go out to the web service and grab the job list.
public async List<Job> GetJSON()
{
List<Job> rootObject = new List<Job>();
try
{
var client = new System.Net.Http.HttpClient();
var response = await client.GetAsync("http://myinternaliis/api/job");
string json = await response.Content.ReadAsStringAsync();
if (json != "")
{
rootObject = JsonConvert.DeserializeObject< List<Job>>(json);
}
}
catch (InvalidCastException e)
{
throw e;
}
return await rootObject;
}
Thanks for help in improving my understanding.
I guess you are looking for something like:
public async Task<T> GetJson<T>(string url)
{
using (var client = new System.Net.Http.HttpClient())
{
var response = await client.GetAsync(url);
var json = await response.Content.ReadAsStringAsync();
return (T)JsonConvert.DeserializeObject<T>(json);
}
}
Usually I have:
IApi - defines all the API methods
IHttpService - defines methods like Get, Post and etc.
IJsonConverter - defines methods like serialize and deserialize.
Here is an example:
public interface IJsonConverter
{
T Deserialize<T>(string json);
string Serialize<T>(T data);
}
public class JsonConveter : IJsonConverter
{
public T Deserialize<T>(string json) => JsonConvert.DeserializeObject<T>(json);
public string Serialize<T>(T data) => JsonConvert.Serialize(data);
}
public interface IHttpService
{
Task<T> Get<T>(string url);
}
public class HttpService : IHttpService
{
readonly IJsonConverter jsonConverter;
public HttpService(IJsonConverter jsonConverter)
{
this.jsonConverter = jsonConverter;
}
public async Task<T> Get<T>(string url)
{
using (var client = new System.Net.Http.HttpClient())
{
var response = await client.GetAsync(url);
var json = await response.Content.ReadAsStringAsync();
return jsonConverter.Deserialize<T>(json);
}
}
}
public interface IApi
{
Task<List<Job>> GetJobs();
}
public class Api : IApi
{
readonly string url = "http://myinternaliis/api/";
readonly IHttpService httpService;
public Api(IHttpService httpService)
{
this.httpService = httpService;
}
public Task<List<Job>> GetJobs() => httpService.Get<List<Job>>($"{url}job");
}
The API I'm calling from my ASP.NET Web API app requires two tokens i.e. accessToken and userToken.
The following code is not working because it takes only the second token, not both. Looks like the second line is over-writing the first one.
How do I add multiple tokens to my request header?
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("APIAccessToken", "token1");
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("UserToken", "token2");
UPDATE:
Here's the way I set this up and it's not working. Basically, my API calls seem to go nowhere. I get no errors. Just no response.
First, I have the HttpClientAccessor that looks like this:
public static class HttpClientAccessor
{
private static Lazy<HttpClient> client = new Lazy<HttpClient>(() => new HttpClient());
public static HttpClient HttpClient
{
get
{
client.Value.BaseAddress = new Uri("https://api.someurl.com");
client.Value.DefaultRequestHeaders.Accept.Clear();
client.Value.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.Value.DefaultRequestHeaders.TryAddWithoutValidation("APIAccessToken", "token1");
client.Value.DefaultRequestHeaders.TryAddWithoutValidation("UserToken", "token2");
return client.Value;
}
}
}
I then have my ApiClient that will perform my API calls which looks like this:
public class MyApiClient
{
HttpClient _client;
public MyApiClient()
{
_client = HttpClientAccessor.HttpClient;
}
public async Task Get()
{
try
{
HttpResponseMessage response = await _client.GetAsync("/myendpoint"); // This is where it gets lost
var data = await response.Content.ReadAsStringAsync();
}
catch(Exception e)
{
var error = e.Message;
}
}
}
This is my controller action:
public class MyController : Controller
{
private readonly MyApiClient _client;
public MyController()
{
_client = new MyApiClient();
}
public IActionResult SomeAction()
{
_client.Get().Wait();
}
}
You are confusing the standard authorization header with custom headers
According to the linked documentation
Request Header
Add the generated tokens to the request headers "APIAccessToken" and "UserToken"
Example Request
APIAccessToken: zjhVgRIvcZItU8sCNjLn+0V56bJR8UOKOTDYeLTa43eQX9eynX90QntWtINDjLaRjAyOPgrWdrGK12xPaOdDZQ==
UserToken: 5sb8Wf94B0g3n4RGOqkBdPfX+wr2pmBTegIK73S3h7uL8EzU6cjsnJ0+B6vt5iqn0q+jkZgN+gMRU4Y5+2AaXw==
To get headers like above, add them to the client like below
_client.DefaultRequestHeaders.TryAddWithoutValidation("APIAccessToken", "token1");
_client.DefaultRequestHeaders.TryAddWithoutValidation("UserToken", "token2");
Based on shown update, the client is adding the headers every time the client is called. This should be in the value factory of the lazy client.
public static class HttpClientAccessor {
public static Func<HttpClient> ValueFactory = () => {
var client = new HttpClient();
client.BaseAddress = new Uri("https://someApiUrl");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("APIAccessToken", "token1");
client.DefaultRequestHeaders.TryAddWithoutValidation("UserToken", "token2");
return client;
};
private static Lazy<HttpClient> client = new Lazy<HttpClient>(ValueFactory);
public static HttpClient HttpClient {
get {
return client.Value;
}
}
}
The controller action also needs to be refactored to avoid deadlocks because of the mixing of async and blocking calls like .Wait() or .Result.
public class MyController : Controller {
private readonly MyApiClient _client;
public MyController() {
_client = new MyApiClient();
}
public async Task<IActionResult> SomeAction() {
await _client.Get();
//... code removed for brevity
}
}
I have MVC project with service like below:
namespace comp.Services
{
public class CompService
{
public HttpClient client = new HttpClient();
public CompService()
{
client.BaseAddress = new Uri("someapiurl");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
protected async Task<string> GetProductAsync(string path)
{
var resp = "nothing here";
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
resp = await response.Content.ReadAsStringAsync();
}
return resp;
}
public string GetProduct(string path)
{
return GetProductAsync(path).GetAwaiter().GetResult();
}
}
}
and actionResult to view:
namespace comp.Controllers
{
public class HomeController : Controller
{
public CompService compService;
public HomeController()
{
compService = new CompService();
}
public ActionResult About()
{
var timeServer = compService.GetProduct("/api/time");
ViewBag.timeServer = timeServer;
return View();
}
}
}
When in debuger I encounter this line:
HttpResponseMessage response = await client.GetAsync(path);
program exit from debuger and there is no respone in browser.
The same code written in console application works.
In VS output is message that response is succes:
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.RemoteDependency","time":"2018-02-18T13:48:31","tags":{"ai.internal.sdkVersion":"rddf:2.2.0-738","ai.internal.nodeName":"DESKTOP-xxxxx","ai.cloud.roleInstance":"DESKTOP-xxxxx"},"data":{"baseType":"RemoteDependencyData","baseData":{"ver":2,"name":"/api/v1/time","id":"xxxxx=","data":"https://api.xxx.com/api/v1/time","duration":"00:00:01.3150000","resultCode":"200","success":true,"type":"Http","target":"xxx","properties":{"DeveloperMode":"true"}}}}
In browser console output:
[14:51:33 GMT+0100 (Central European Standard Time)] Browser Link: Failed to send message to browser link server:
Error: SignalR: Connection must be started before data can be sent. Call .start() before .send()
Thanks for help.
You should really keep the code async all the way through in stead of trying to mix synchronous and asynchronous code
namespace comp.Services {
public class CompService {
static HttpClient client = new HttpClient();
static CompService() {
client.BaseAddress = new Uri("someapiurl");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<string> GetProductAsync(string path) {
var resp = string.Empty;
using(var response = await client.GetAsync(path)) {
if (response.IsSuccessStatusCode) {
resp = await response.Content.ReadAsStringAsync();
}
}
return resp;
}
}
}
The controller action should also be made async
namespace comp.Controllers {
public class HomeController : Controller {
private CompService compService;
public HomeController() {
compService = new CompService();
}
public async Task<ActionResult> About() {
var timeServer = await compService.GetProductAsync("api/time");
ViewBag.timeServer = timeServer;
return View();
}
}
}
That said, the service should also be abstracted
public interface ICompService {
Task<string> GetProductAsync(string path)
}
public class CompService : ICompService {
//...code removed for brevity
}
and injected into the controller instead of creating it manually.
public class HomeController : Controller {
private ICompService compService;
public HomeController(ICompService compService) {
this.compService = compService;
}
public async Task<ActionResult> About() {
var timeServer = await compService.GetProductAsync("api/time");
ViewBag.timeServer = timeServer;
return View();
}
}
Reference Async/Await - Best Practices in Asynchronous Programming
What you've got is a deadlock. Unlike console apps, ASP.Net applications run in a Synchronization Context. That context is captured when you block with GetResult(). Then, in GetProductAsync, you await on the context that is blocked. It cannot resume until GetResult is done which cannot resolve until the await is done.
#NKosi 's answer should resolve the problem, there is no reason for you to have any synchronous code.
For demonstration only
You can hack your code to work by explicitly allowing your await to run on a different context. You should not do this in production, it is not a fix. It can fail if someone maintaining the CompService is not careful.
To await against a different context change this:
var timeServer = await compService.GetProductAsync("api/time");
To this:
var timeServer = await compService.GetProductAsync("api/time").ConfigureAwait(false);
I mention this only to help you understand what is happening in your code. Don't "fix" it this way and move on.
I have this block of code in my Xamarin PCL project. However, on line 4 where it is meant to call the GetStringAsync method, code exits the method at that point and returns no response. I am unable to get json data from the web service and have tried several workarounds without success. I am using Visual studio 2015.
//this calls the webservice
public class RestClient<T>
{
private const string WebServiceUrl = "http://localhost:14241/api/Employees/";
public async Task<List<T>> GetAsync()
{
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(WebServiceUrl);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
public async Task<bool> PostAsync(T t)
{
var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(t);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = await httpClient.PostAsync(WebServiceUrl, httpContent);
return result.IsSuccessStatusCode;
}
public async Task<bool> PutAsync(int id, T t)
{
var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(t);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = await httpClient.PutAsync(WebServiceUrl + id, httpContent);
return result.IsSuccessStatusCode;
}
public async Task<bool> DeleteAsync(int id, T t)
{
var httpClient = new HttpClient();
var response = await httpClient.DeleteAsync(WebServiceUrl + id);
return response.IsSuccessStatusCode;
}
}
//this is the main view model that binds to the XAML page
public class MainViewModel : INotifyPropertyChanged
{
private List<Employee> _employeeList;
public List<Employee> EmployeesList
{
get { return _employeeList; }
set
{
_employeeList = value;
OnPropertyChanged();
}
}
public MainViewModel()
{
InitializeDataAsync();
}
private async Task InitializeDataAsync()
{
var employeeServices = new EmployeesServices();
EmployeesList = await employeeServices.GetEmployeesAsync();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName=null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
//method that calls the GetAsync() method to retrieve the employee list
//from the web service
public class EmployeesServices
{
public async Task<List<Employee>> GetEmployeesAsync()
{
RestClient<Employee> restClient = new RestClient<Employee>();
var employeesList = await restClient.GetAsync();
return employeesList;
}
}
Make sure you are using await on the entire call chain all the way down to GetAsync().