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.
Related
Im trying to POST the following API using C# when a user presses a button on a form. However no idea where to start. Can anyone help ?
Button Code
private void Okta_Click(object sender, RoutedEventArgs e)
{ }
POST : https://test.okta.com/api/v1/authn
Body
{
"username": "user",
"password": "password",
"options": {
"multiOptionalFactorEnroll": true,
"warnBeforePasswordExpired": true
}
}
When the user presses the button, it should add the user to the application.
You can use the HttpClient class to make the request.
private async void Okta_Click(object sender, RoutedEventArgs e)
{
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://test.okta.com/api/v1/authn");
request.Content = new StringContent("{\"username\": \"user\",\"password\": \"password\",\"options\": {\"multiOptionalFactorEnroll\": true,\"warnBeforePasswordExpired\": true}}", Encoding.UTF8, "application/json");
var response = await client.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();
}
I am building a c# forms application that is calling a .net core API
Code in the forms application is as follows
static HttpClient client = new HttpClient();
private async void btn_callAPI_Click(object sender, EventArgs e)
{
this.TopMost = false;
client.BaseAddress = new Uri("https://localhost:44377/api/values/url/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync("1");
MessageBox.Show(response.Content.ToString());
client = new HttpClient();
}
The API I am calling is doing the following operation:
[HttpGet("url/{id}")]
public string Gets(int id)
{
return "value2";
}
I want the message box to access the value returned by the API which in this case is a string value2.
How do I access the data returned by the API?
var response = await client.GetAsync("1");
string result = await response.Content.ReadAsStringAsync();
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 am making HTTP Post call to a webservice url. In the response I get 200 Status Ok message. But when I try to get the response content using await response.Content.ReadAsStringAsync() its always '{}'. The web service returns either SUCCESS or FAILED based on the user credentials passed. How do I retrieve the message. Please help.
Code to make a web service call
public Task<HttpResponseMessage> PostAsJsonAsync<T>(Uri uri, T item)
{
var client = new HttpClient();
var itemAsJson = JsonConvert.SerializeObject(item);
var content = new StringContent(itemAsJson);
//var content = new FormUrlEncodedContent(itemAsJson);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Clear();
return client.PostAsync(uri, content);
}
private async void mainPage_Loaded(object sender, RoutedEventArgs e)
{
UserDetails details = new UserDetails()
{
username = composite["username"].ToString(),
userpass = composite["password"].ToString()
};
var response = await PostAsJsonAsync(new Uri("http://ec2-xxxx-.compute-1.amazonaws.com:8080/Sanjeevani/rest/SV/login"), details);
if (response.IsSuccessStatusCode) //I get a 200 code i.e OK
{
string str = await response.Content.ReadAsStringAsync();
if (str == "SUCCESS") //str is always '{}'
{
this.Frame.Navigate(typeof(Dashboard), details);
}
}
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);