im trying to send a HTTP POST request from xamarin forms app to a webservice API on ASP.NET MVC, However, when i do it, i get status code 500 back from the server. I suspect it has something to do with the values in sending to API but i have not been able to figure it out.
Anyhelp is much appeciated
here is the
WEB API CODE
public void LogInFromMobile([FromBody] List<Creds> detail)
{
......
}
here is the
XAMARIN-FORMS APP CODE
public async void Button_Clicked(object sender, EventArgs e)
{
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Creds cr = new Creds();
cr.username = user.Text;
cr.password = pass.Text;
List<Creds> cred = new List<Creds>();
cred.Add(cr);
string url = #"http://IPHERE/LoginWebService.asmx/LogInFromMobile";
string json = JsonConvert.SerializeObject(cred);
HttpContent content = new StringContent(json);
var response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
await DisplayAlert("Alert", "Success", "Ok");
return;
}
else
{
await DisplayAlert("Alert", "Error", "Ok");
return;
}
}
}
catch(Exception ex)
{
await DisplayAlert("", ex.Message, "ok");
}
}
Related
I'm implementing JWT Auth with Xamarin forms. Now auth looks working from server side and I'm trying to test if it is working as expected on client side. My server app is running on local machine but emulator already configured to send traffic to my domain.
Here is my Xamarin.Forms Test method sending Request for testing:
async Task Test()
{
try
{
var token = await SecureStorage.GetAsync("access_token");
string url = "https://example.com:44330/account/testauth";
using (var httppClient = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(url),
Headers =
{
{ "Authorization", $"Bearer {token}" }
}
};
var response = await httppClient.SendAsync(request);
string respStr = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
//Do something
}
}
}
catch (Exception ex)
{
//handle exception
}
}
After sending a request I'm getting an error Failed to connect to example.com/52.202.22.6:44330.
What configuration could be missed considering that WebAuthenticator.AuthenticateAsync works fine for the same domain?
I have implemented SqlBotDataStore for bot storage but the LoadAsync method is silently failing. This is in the MessageController's POST. No exceptions are thrown anywhere, it just stops at this line, the chat bot continues as if nothing ever happened but storage does not work:
var botDataStore = scope.Resolve<IBotDataStore<BotData>>();
var key = Address.FromActivity(activity);
try
{
var userData = await botDataStore.LoadAsync(key, BotStoreType.BotPrivateConversationData, CancellationToken.None);
userData.SetProperty<Translator>("translator", new Translator());
userData.SetProperty<bool>("autoDetectLanguage", true);
userData.SetProperty<bool>("autoTranslateToBot", true);
userData.SetProperty<bool>("autoTranslateToUser", true);
await botDataStore.SaveAsync(key, BotStoreType.BotPrivateConversationData, userData, CancellationToken.None);
}
catch (HttpException e)
{
Debug.WriteLine(e.Message);
}
I cannot seem to get past this and unfortunately don't have any more information because literally no error or anything happens here. When debugging it just never goes to the next line and continues execution silently.
Based on this github sample using Azure Sql Storage to store the bot state, I modify the sample with following updates and do a test, which work for me. You can compare the sample with your implementation to find differences.
In MessagesController:
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type == ActivityTypes.Message)
{
if (activity.Text == "savetest")
{
var message = activity as IMessageActivity;
using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
{
var botDataStore = scope.Resolve<IBotDataStore<BotData>>();
var key = Address.FromActivity(activity);
try
{
var userData = await botDataStore.LoadAsync(key, BotStoreType.BotPrivateConversationData, CancellationToken.None);
//userData.SetProperty<Translator>("translator", new Translator());
userData.SetProperty<bool>("autoDetectLanguage", true);
userData.SetProperty<bool>("autoTranslateToBot", true);
userData.SetProperty<bool>("autoTranslateToUser", true);
await botDataStore.SaveAsync(key, BotStoreType.BotPrivateConversationData, userData, CancellationToken.None);
await botDataStore.FlushAsync(key, CancellationToken.None);
}
catch (HttpException e)
{
Debug.WriteLine(e.Message);
}
}
}
await Conversation.SendAsync(activity, () => new Dialogs.EchoDialog());
}
else
{
HandleSystemMessage(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
In EchoDialog:
var tval = context.PrivateConversationData.GetValueOrDefault<bool>("autoTranslateToBot", false);
await context.PostAsync("You said: " + message.Text + $"; autoTranslateToBot is {tval.ToString()}");
context.Wait(MessageReceivedAsync);
Test result:
My code for class AllWebApiOperations is
public AllWebApiOperations(string apiURI)
{
client = new HttpClient();
client.BaseAddress = new Uri(apiURI);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<string> GetDataAsync(string route)
{
string result= string.Empty;
HttpResponseMessage response = await client.GetAsync(route);
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsAsync<string>();
}
return result;
}
I'm calling this in button click
string apiURI = #"http://localhost:35487/";
private async void btnCallWebApi_Click(object sender, EventArgs e)
{
AllWebApiOperations op = new AllWebApiOperations(apiURI);
var result = await op.GetDataAsync(apiURI + "api/products/");
Console.WriteLine(result);
}
My code web api is working properly as shown below
But I'm getting error while calling the function as shown below
I'm not sure why I'm getting this error, tried googling but can't find resolution.
Found the answer:
public async Task<string> GetDataAsync(string route)
{
string result= string.Empty;
HttpResponseMessage response = await client.GetAsync(route);
if (response.IsSuccessStatusCode)
{
**result = await response.Content.ReadAsAsync<string>();**
}
return result;
}
I should be using
**result = await response.Content.ReadAsStringAsync();**
I have paypal integration application which receives webhook notification from paypal and I want to verify the signature as per docs:
Verify signature rest api link
Here is code which I have written:
public async Task<ActionResult> Index()
{
var stream = this.Request.InputStream;
var requestheaders = HttpContext.Request.Headers;
var reader = new StreamReader(stream);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
var webhook = serializer.Deserialize<Models.Event>(jsonReader);
var webhookSignature = new WebhookSignature();
webhookSignature.TransmissionId = requestheaders["PAYPAL-TRANSMISSION-ID"];
webhookSignature.TransmissionTime = requestheaders["PAYPAL-TRANSMISSION-TIME"];
webhookSignature.TransmissionSig = requestheaders["PAYPAL-TRANSMISSION-SIG"];
webhookSignature.WebhookId = "My actual webhookid from paypal account";
webhookSignature.CertUrl = requestheaders["PAYPAL-CERT-URL"];
webhookSignature.AuthAlgo = requestheaders["PAYPAL-AUTH-ALGO"];
webhookSignature.WebhookEvent = webhook;
var jsonStr2 = JsonConvert.SerializeObject(webhookSignature);
var result = await _webhookService.VerifyWebhookSignatureAsync(webhookSignature);
var jsonStr3 = JsonConvert.SerializeObject(result);
return Content(jsonStr3, "application/json");
}
public async Task<Models.SignatureResponse> VerifyWebhookSignatureAsync(Models.WebhookSignature webhook, CancellationToken cancellationToken = default(CancellationToken))
{
var accessTokenDetails = await this.CreateAccessTokenAsync();
_httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessTokenDetails.AccessToken);
try
{
string jsonStr = JsonConvert.SerializeObject(webhook);
var content = new StringContent(jsonStr, Encoding.UTF8, "application/json");
string url = $"{_baseUrl}notifications/verify-webhook-signature";
var response = await _httpClient.PostAsync(url, content);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync();
throw new Exception(error);
}
string jsonContent = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<Models.SignatureResponse>(jsonContent);
}
catch (Exception ex)
{
throw new InvalidOperationException("Request to Create payment Service failed.", ex);
}
}
Webhook signature verification response :
{"verification_status":"FAILURE"}
I am getting 200K ok response from api but verification status in response is always FAILURE.I tried many different request.
I am not sure if something is wrong from my request. Looking for help.
I want to get specific data from a action in a webAPI controller to my windows mobile app .here is my webAPI action;
// GET: api/Customer/5
[ResponseType(typeof(Customer))]
public IHttpActionResult GetValidCustomer(string username,string password)
{
var customer = (from cust in db.Customers
where cust.CustomerName == username && cust.CustomerPw == password
select cust).ToList();
if (customer == null)
{
return NotFound();
}
else
{
return Ok(customer);
}
}
I have tried to consume that action as follows,but the windows emulator starts to freeze when I use that method.
public async System.Threading.Tasks.Task<bool> isValidUser(string username,string password)
{
try
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:2335");
var url = "api/Customer?username="+username+"&password="+password;
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
}
else
{
}
}
}
catch (Exception ex)
{
return false;
}
}