Xamarin.forms webservice to azure database - c#

I am a newbie in Xamarin and I am looking for a way to send information to the azure database with Xamarin.forms, I am using webservice.
What I have done:
1-I have already created my azure database online
2-I have make the code to send information
Problem:
1-I do not know what I have to put in client.PostAsync to sending my information (email ,password, confirmpassword)
Here is the code :
public class ApiServices
{
public async Task <bool> RegisterAsync(string email, string password, string confirmPassword)
{
var client = new HttpClient();
var model = new RegisterBindingModel
{
Email=email,
Password=password,
ConfirmPassword= confirmPassword
};
// to send my information
var json = JsonConvert.SerializeObject(model);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// what do I need to put in PostAsync?
var response= await client.PostAsync("",content);
return response.IsSuccessStatusCode;
}
}
Thanks in advance . if you have better solution and somme information to know , I will take it.

First argument of PostAsync must be Uri of Service, e.g. http://mywebservice.com/api/user

Related

C# Post Variables can't be read on Website - HttpClient PostAsync()

I have a web server on which I'm hosting my own api for one of my projects.
This is the php-code of the api-website:
$user = $_POST['username'];
$password = $_POST['password'];
if(strcmp($user, "username") == 0 && strcmp($password, "password") == 0) {
...
} else {
die("No Permissions");
}
I want to send the two variables username and password with a HttpClient and the postAsync-method to this website and if the right log in data is detected, it returns the data I want.
For this I have the following code in C#:
Task<HttpResponseMessage> response;
var url = "www.url.de"; //not the url I'm actually calling!
var vars = "[{\"username\":\"username\", \"password\":\"password\"}]";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
response = client.PostAsync(url, new StringContent(vars, Encoding.UTF8));
Console.WriteLine(response.Result.Content.ReadAsStringAsync().Result);
if (response.IsCompleted)
{
Console.WriteLine(response.Result.Content.ReadAsStringAsync().Result);
}
}
But the problem is that no matter what I have tried the output from this code is, that i have no permissions. And I have changed the php-code, so that I can see which data is stored in $username and $password, but they are empty and I don't know why. I hope somebody can help me with this.
Your PHP code is expecting the data sent as application/x-www-form-urlencoded, but your C# code is sending it as JSON.
As mentioned in the comment by M. Eriksson, you either need to change your PHP to accept JSON, or change your C# to send as form data.
This answer shows how to use HTTPClient to send data like that.
Here's my modification of your code based on the above code (I did test it):
public static async Task DoSomething()
{
string url = "http://httpbin.org/post"; //not the url I'm actually calling!
Dictionary<string, string> postData = new();
postData["username"] = "username";
postData["password"] = "password";
using HttpClient client = new();
client.DefaultRequestHeaders.Accept.Add(new("application/json"));
HttpRequestMessage request = new(HttpMethod.Post, url);
request.Content = new FormUrlEncodedContent(postData);
HttpResponseMessage response = await client.SendAsync(request);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}

Not getting any responses from my http requests (System.Net.Http.HttpRequestException: 'Request aborted')

I am trying to consume my REST API using Xamarin with a POST request. However; I never get any responses to my web requests. The app just keeps awaiting them for minutes before finally throwing a System.Net.Http.HttpRequestException: 'Request aborted' exception.
I have tried the same exact code in a .NET console application, where it works fine:
using Newtonsoft.Json;
using RestSharp;
Console.Write("Email: ");
string email = Console.ReadLine();
Console.Write("Password: ");
string password = Console.ReadLine();
string jwcUrl = "[URL]";
RestClient client = new RestClient(jwcUrl);
object data = new
{
email = email,
password = password
};
var myContent = JsonConvert.SerializeObject(data);
var request = new RestRequest().AddStringBody(myContent, DataFormat.Json);
var response = await client.PostAsync(request);
Console.WriteLine(response.Content);
The call gets through and eventually, I get my response. Not in the Xamarin app though. The function gets called from the OnClick over here:
public async void OnClick(View v)
{
var emailInput = FindViewById<EditText>(Resource.Id.inputEmail);
var passwordInput = FindViewById<EditText>(Resource.Id.inputPassword);
var responseTextField = FindViewById<TextView>(Resource.Id.twResponse);
UserController userController = new UserController();
string response = await userController.LogIn(emailInput.Text, passwordInput.Text);
Toast.MakeText(Application.Context, response, ToastLength.Long).Show();
responseTextField.Text = response;
}
The code of which is here:
using RollCallAndroid.Models;
using RestSharp;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace RollCallAndroid.Controllers
{
public class UserController
{
private const string jwcUrl = "[URL]";
public async Task<string> LogIn(string email, string password)
{
User user = new User();
RestClient client = new RestClient(jwcUrl);
object data = new
{
email = email,
password = password
};
var myContent = JsonConvert.SerializeObject(data);
var request = new RestRequest().AddStringBody(myContent, DataFormat.Json);
var response = await client.GetAsync(request);
return response.StatusCode.ToString();
}
}
}
The issue isn't with RestSharp, the same thing happens when using the normal HttpClient. Even when trying a simple GetAsync on the default WeatherForecast, I get no response, no status code, nothing. Just silence until Visual Studio tells me the request was aborted.
Does anyone have any idea what's wrong? I'm out of ideas since the same request works fine everywhere else (Swagger, Postman, Console app). Thanks.
Usually for android when you have this kind of issue changing the SSL/TLS implementation to Native TLS 1.2+ helps, look at this answer

POST from Form to external API

I'm quite noob into asp.net
I'm building a simple solution in VS2019, using asp.net MVC, which is supposed to send a User data to another API which will be responsible for saving into database.
So far, both APIs are REST and I'm not using core
Basically, it is a form with a submit that will POST to the external project, pretty simple.
I'm following some tutorials and stuff but there are so many different ways that got me confused, so I decided to ask here
Here's what I have so far
[HttpPost]
public async ActionResult Index(User user)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://pathtoAPI.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
User newuser = new User()
{
email = user.email,
nome = user.nome,
cpf = user.cpf,
cnpj = user.cnpj,
userName = user.userName,
senha = user.senha,
telefone = user.telefone
};
var jsonContent = JsonConvert.SerializeObject(newuser);
var contentString = new StringContent(jsonContent, Encoding.UTF8, "application/json");
contentString.Headers.ContentType = new
MediaTypeHeaderValue("application/json");
//contentString.Headers.Add("Session-Token", session_token);
HttpResponseMessage response = await client.PostAsync("register", contentString);
return Content($"{response}");
}
I want to receive the "OK" message from the other API and just print it on my screen, I'm using the cshtml file to handle the front and the form as well.
The return though seems to be wrong, it's expecting either 'null, task, task, or something like.
Can someone please help me with this code?
Thanks
You need to return the content of the response, not the response object itself.
HttpResponseMessage response = await client.PostAsync("register", contentString);
string responseBody = await response.Content.ReadAsStringAsync();
return Content(responseBody);

Twilio Authy 2FA for OneCode C# Implementation

I am developing a web application using C# that uses 2 factor authentication during Sign Up. I have already tried 2FA using Nexmo's API. It worked fine. All I had to do was call their API and speciy the 'to' number. Here is the code:
public ActionResult Start(string to)
{
var start = NumberVerify.Verify(new NumberVerify.VerifyRequest
{
number = to,
brand = "NexmoQS"
});
Session["requestID"] = start.request_id;
return View();
}
Now, I decided to give Twilio a try. I came across Authy and it's process. I found their 2FA API here. But I don't understand where should I enter the 'to' number as specified in Nexmo. I am a beginner and using .NET(C#) code snippet. Here is the code snippet. Please help me configure this code as I am able to do in Nexmo.
public static async Task VerifyPhoneAsync()
{
// Create client
var client = new HttpClient();
// Add authentication header
client.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthyAPIKey);
// https://api.authy.com/protected/$AUTHY_API_FORMAT/phones/verification/check?phone_number=$USER_PHONE&country_code=$USER_COUNTRY&verification_code=$VERIFY_CODE
HttpResponseMessage response = await client.GetAsync("https://api.authy.com/protected/json/phones/verification/check?phone_number=5558675309&country_code=1&verification_code=3043");
// Get the response content.
HttpContent responseContent = response.Content;
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
Console.WriteLine(await reader.ReadToEndAsync());
}
}
They have given a cURL implementation of their api here, please help me configure it in C#.
curl "http://api.authy.com/protected/json/users/new?api_key=d57d919d11e6b221c9bf6f7c882028f9" \
-d user[email]="user#domain.com" \
-d user[cellphone]="317-338-9302" \
-d user[country_code]="54"
Twilio developer evangelist here.
When making a call to the API, you do need to add the X-Authy-API-Key header as well as a URL parameter api_key. Also, to start the process of verifying a number you should be making a POST request with the data you need to send to the API.
The two bits of data that you need are the phone number and the country code for that phone number. Though you can set some other values, like the way you want to send the verification code (via sms or call).
I would update your code to look like this:
public static async Task StartVerifyPhoneAsync()
{
// Create client
var client = new HttpClient();
var AuthyAPIKey = 'YOUR AUTHY API KEY';
// Add authentication header
client.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthyAPIKey);
var values = new Dictionary<string, string>
{
{ "phone_number", "PHONE NUMBER TO VERIFY" },
{ "country_code", "COUNTRY CODE FOR PHONE NUMBER" }
};
var content = new FormUrlEncodedContent(values);
var url = $"https://api.authy.com/protected/json/phones/verification/start?api_key={AuthyAPIKey}";
HttpResponseMessage response = await client.PostAsync(url, content);
// do something with the response
}
Then when the user enters the code, you need to check it. Again you should add the API key as a header and send as a URL parameter too, along with the phone number, country code and the verification code the user entered, this time as a GET request.
public static async Task CheckVerifyPhoneAsync()
{
// Create client
var client = new HttpClient();
var AuthyAPIKey = 'YOUR AUTHY API KEY';
// Add authentication header
client.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthyAPIKey);
var phone_number = "PHONE NUMBER TO VERIFY";
var country_code = "COUNTRY CODE FOR PHONE NUMBER";
var verification_code = "THE CODE ENTERED BY THE USER";
var url = $"https://api.authy.com/protected/json/phones/verification/start?api_key={AuthyAPIKey}&phone_number={phone_number}&country_code={country_code}&verification_code={verification_code}";
HttpResponseMessage response = await client.GetAsync(url);
// do something with the response
}
Let me know if that helps at all.

Can I check Userlogin Username and Password with a REST Service in Xamarin Android?

hi i build a xamarin android application and have three activities for a loginsystemn.
I want to use a REST Service for checking the Username and Password.
What is the best way to check username and password in a mobile application and how make it? Can I use a REST Service for check the user data?
Reference
https://developer.xamarin.com/guides/xamarin-forms/web-services/consuming/rest/
https://stackoverflow.com/posts/36460334/edit
From above link
A simple example:
var client = new HttpClient();
client.BaseAddress = new Uri("localhost:8080");
string jsonData = #"{""username"" : ""myusername"", ""password"" : ""mypassword""}"
var content = new StringContent (jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("/foo/login", content);
// this result string should be something like: "{"token":"rgh2ghgdsfds"}"
var result = await response.Content.ReadAsStringAsync();
Where "/foo/login" will need to point to your HTTP resource. For example, if you have an AccountController with a Login method, then instead of "/foo/login" you would use something like "/Account/Login".
You can use post service to send username and password in RequestBody in json formate and get the response from server for the same.

Categories