WPF / C# Submit button to POST API - c#

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();
}

Related

sending headrs to web API from winForm client

i have a simple demo winform app and im trying to make a post request with header to web api.
i received access token and refreash token form the server and i stored that in text file.
and im trying to make a post request by sending the refreash token with the body and sending the access token with the header but i dont know how to include the header with the post request.
this my post method
public static async Task<string> sendMessage(string name, string contents)
{
using (HttpClient client = new HttpClient())
{
//reading the access token and refreash token from file
StreamReader sr = new StreamReader(#"C:\Users\noorm\Desktop\noor.txt");
string accessToken, refreashToken;
accessToken = sr.ReadLine();
refreashToken = sr.ReadLine();
//defining new instance of message opject
var newMessage = new messages()
{
name = name,
content = contents,
refreashToken = refreashToken
};
//sening the opject using post async and returning the response
var newPostJson = JsonConvert.SerializeObject(newMessage);
var payLoad = new StringContent(newPostJson, Encoding.UTF8, "application/json");
using (HttpResponseMessage res = await client.PostAsync(baseURL + "/messages", payLoad))
{
using (HttpContent content = res.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
return data;
}
}
}
}
return string.Empty;
}
and this is the button
private async void btnSend_Click(object sender, EventArgs e)
{
var responce = await restHelper.sendMessage(txtName.Text.Trim(),txtContent.Text.Trim());
rtxt.Text = responce;
}
You can try something like the following:
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");
this is how i was able to send the access token with the header
client.DefaultRequestHeaders.Add("x-auth-token", accessToken);

How to display a value returned by .net core api?

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();

Strange behavior of WPF app accessing Web API

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.

Response content of HttpResponseMessage on making a Post request is always '{}' in uwp

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);
}
}

How to know when a A-Synchronous REST call in Windows 8.1 Mobile Library has been completed?

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;
.....

Categories

Resources