I am having problem in calling the HttpClient post method from WP application.The PostAsync always hangs and does not give any response.The same code works when i try it from WPF application. Here is what I am doing:
Server Web API code
public class GameController : ApiController
{
[HttpPost]
public GameDto CreateGame(GameDto gameDto)
{
try
{
GameManager bl = new GameManager();
gameDto = bl.CreateGame(gameDto);
return gameDto;
}
catch (Exception)
{
throw;
}
}
}
Client WP8 code calling from class library
private async void Button_Click(object sender, RoutedEventArgs e)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:59580");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
GameDto newGame = new GameDto();
newGame.CreatedBy = 1;
newGame.Name = txtGameName.Text;
newGame.GameTypeId = (int)cmbGameType.SelectedValue;
MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
var response = await client.PostAsync<GameDto>("api/Game/CreateGame", newGame, jsonFormatter);
response.EnsureSuccessStatusCode(); // Throw on error code.
var userDto = await response.Content.ReadAsAsync<GameDto>();
//_products.CopyFrom(products);
MessageBox.Show(userDto.Id.ToString());
}
catch (Exception)
{
throw;
}
}
Checkout This
Answer res.olved my issue.
Use ConfigureAwait
var result = await httpClient.GetStreamAsync("weeklyplan")
.ConfigureAwait(continueOnCapturedContext:false);
Related
I have a WPF app which I use it to pull data from a Web API.
After login I store the token and based on that you can access the API or not.
Case 1: Login, get token, click button to get data:
private async void button1_Click(object sender, RoutedEventArgs e)
{
getMovies();
}
Method implemented
private void getMovies()
{
var accessToken = token;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
client.BaseAddress = new Uri("http://localhost:5001/movies/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("get").Result;
if (response.IsSuccessStatusCode)
{
MessageBox.Show(response.Content.ReadAsStringAsync().Result);
}
else
{
MessageBox.Show("Movies not Found");
}
}
And I receive back a 401.
Case 2: I call the API from the Start method (same code as above): get data from API
public async void Start(object sender, RoutedEventArgs e)
{
getMovies();
}
How is this possible? And how can I do to access my API outside of the Start method?
The method should first be refactored to follow commonly suggested syntax
string baseUrl = "http://localhost:5001/movies/"
private async Task getMoviesAsync() {
var accessToken = token; //assuming token is being retrieved and set somewhere else
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync("get");
if (response.IsSuccessStatusCode) {
MessageBox.Show( await response.Content.ReadAsStringAsync());
} else {
MessageBox.Show("Movies not Found");
}
}
and called as follows
private async void button1_Click(object sender, RoutedEventArgs e) {
await getMoviesAsync();
}
Creating HttpClient on ever call is usually not advised but that is off-topic for the current problem at hand.
I'm learning how to create WEB-API client
I've created some simple API:
[HttpGet]
public IHttpActionResult GetInfo()
{
return Ok("Its working!");
}
[HttpPost]
public IHttpActionResult PostInfo(ClientDataDto dto)
{
try
{
someMethod(dto.IdKlienta, dto.Haslo, dto.IdZgloszenia, dto.HardwareInfo, dto.SoftwareInfo);
return Ok("sent");
}
catch
{
return BadRequest();
}
}
For now I just trying to call GET method.
When I use Fiddler with addr
localhost:someport/api/Client2
its working
but when i try to do it by client, which code is below:
private static HttpClient client = new HttpClient();
static void Main(string[] args)
{
#region TESTONLY
var debug = new XMLData();
string HardwareInfoXML = debug.HardwareXML;
string SoftInfoXML = debug.SoftwareXML;
int id_zgloszenia = 20;
int idKlienta = 25;
//haslo = "202cb962ac59075b964b07152d234b70";
#endregion
var data = new ClientDataDto() { HardwareInfo = HardwareInfoXML, SoftwareInfo = SoftInfoXML, IdKlienta = idKlienta, IdZgloszenia = id_zgloszenia };
RunAsync(data);
}
private static async Task RunAsync(ClientDataDto data)
{
var stringContent = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri(#"http://localhost:7774/api/client2/");
var url = new Uri(#"http://localhost:7774/api/client2/");
var res1 = await client.GetAsync(url);
var res = await client.PostAsync(url, stringContent);
res.EnsureSuccessStatusCode();
}
Application closing without any info at
var res1 = await client.GetAsync(url);
I have checked to see all exceptions in Debug exception Windows, but it is just closing after trying call GetAsync
PostASync doesn't work too.
What is wrong here?
i'm really sorry that i've posted simpe problem.
sulotion is to add .Wait() on RunAsync(data);
RunAsync(data).Wait();
Hello i have created two examples but i am not sure if any of these are correct. I want to create a new task and call asynchronously a web api c#.Below there are both of the examples.
The first example:
private string APIResponse()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:55517/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/Values").Result;
if (response.IsSuccessStatusCode)
{
var products = response.Content.ReadAsStringAsync().Result;
//Thread.Sleep(5000);
return products.ToString();
}
else
{
return "ERROR";
}
}
protected async void Apibtn_Click(object sender, EventArgs e)
{
Task<string> task = new Task<string>(APIResponse);
task.Start();
var ApiResp = await task;
Do some work here...
// ...
//..
//.
}
And the second example is :
private async Task<string> APIResponse()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:55517/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/Values");
if (response.IsSuccessStatusCode)
{
var products = await response.Content.ReadAsStringAsync();
//Thread.Sleep(5000);
return products.ToString();
}
else
{
return "ERROR";
}
}
protected async void Apibtn_Click(object sender, EventArgs e)
{
Task<string> task = APIResponse();
// task.Start(); //You don't need to start the Tasks returned by
async method calls. They're started by default.
var ApiResp = await task;
//Do some work here...
//...
//..
//.
}
If none of the above is correct could you please give me an example? Thanks!
Your second example is almost correct, just do something like this instead:
private async Task<string> APIResponse()
{
using (HttpClient client = new HttpClient())
{
...
HttpResponseMessage response = await client.GetAsync("api/Values");
...
}
}
protected async void Apibtn_Click(object sender, EventArgs e)
{
var apiResp = await APIResponse();
}
Don't forget the using statement on IDisposable members (such as HttpClient)
The second example is correct; you should never use Task.Result.
However, there is no need for a separate task variable at the end; you can await the call directly.
I wrote simple method for getting data from (online) REST Service:
public async Task<Object> GetTask()
{
try
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://111.111.111.111:8080/");
HttpResponseMessage result = await client.GetAsync("ABC/CDE/getsomeinfo");
if (result.IsSuccessStatusCode)
{
//Deserialize
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Error" + ex);
}
return null;
}
Whenever i run this on UWP i'm getting catch exception:
The text associated with this error code could not be found.
A connection with the server could not be established
HResult 2147012867
Im trying to connect my client with restapi in internal network. In forms same code is working properly.
Try this
HttpResponseMessage response;
public async Task<string> webserviceResponse(string HttpMethod)
{
// check internet connection is available or not
if (NetworkInterface.GetIsNetworkAvailable() == true)
{
// CancellationTokenSource cts = new CancellationTokenSource(2000); // 2 seconds
HttpClient client = new HttpClient();
MultipartFormDataContent mfdc = new MultipartFormDataContent();
mfdc.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
string GenrateUrl = "your url";
if (HttpMethod == "POST")
{
response = await client.PostAsync(GenrateUrl, mfdc);
}
else if (HttpMethod == "PUT")
{
response = await client.PutAsync(GenrateUrl, mfdc);
}
else if (HttpMethod == "GET")
{
response = await client.GetAsync(GenrateUrl);
}
var respon = await response.Content.ReadAsStringAsync();
string convert_response = respon.ToString();
return convert_response;
}
else
{
return "0";
}
}
Background::
I am creating a Windows 8.1 Mobile SDK that will have a License Manager(LM) Module.
The client will have to Call The License Manager in their code once whenever the application starts.
The license manager will register the client and send a set of JSON Response that will be stored on the device for future validations.
The License Manager function makes REST Calls to our server.
Problem::
What will be the best place within a Windows 8.1 application to call the License Manager Function provided in the SDK?
How to make the call to the LM Synchronous, so that the client gets a chance to handle responses in case the license is not validated. Or before the client calls the other APIs included in the SDK.
Work Done::
I have created the LM function and returns the desired results.
Created a Demo App that calls the LM on a button click.
Please find the sample code below,
Client Application:
private async void Button_Click(object sender, RoutedEventArgs e)
{
try
{
var x = await sdk.InitializeAsync("xxxxxxx-xxx-xxxx");
//Calling an API included in the SDK
APIResponse res = await laas.Function1_Async(par1, par2);
msg.Text = x.ToString();
}
catch (Exception ex)
{
}
}
SDK:
public async Task<int> InitializeAsync(string apiKey)
{
int status = 0;
if (!_isInitialized)
{
status = await GetLicenseInfo(localSettings);
}
this._isInitialized = true;
return status;
}
private async Task<int> GetLicenseInfo(Windows.Storage.ApplicationDataContainer localSettings)
{
APIResponse res = new APIResponse();
res.Status = -10;
res.Message = "Unknown Error!";
// Create the web request
StringBuilder data = new StringBuilder();
data.Append(*JSON String*);
string Uri = _regisUrl;
using (HttpClient client = new HttpClient())
{
Uri url = new Uri(Uri);
StringContent content = new StringContent(data.ToString(), Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Host = url.Host;
try
{
using (HttpResponseMessage response = await client.PostAsync(url, content))
{
if (response.IsSuccessStatusCode)
{
res = JsonConvert.DeserializeObject<APIResponse>(await response.Content.ReadAsStringAsync());
//Check that the Response is Success
if (res.Status == 1)
localSettings.Values["IsDeviceRegistered"] = StringCipher.Encrypt("registered");
}
}
}
catch
{
}
}
return res.Status;
}
Any Help would be appreciated.
This will change your code to be Synchronous...
Task<int> t = sdk.InitializeAsync("xxxxxxx-xxx-xxxx");
t.Wait();
var myvalue = t.Result;
.....