HttpClient.PostAsync causes infinite Loop when calling at Page_Load - c#

I have this Web Api call in my code behind. This is for my Single-Sign-On using Windows credential from our AD. What it did is just call the Web Api and check if the User is Authenticated and have access to the App.
I successfully call my Web Api using HttpClient.PostAsync but I'm wondering why it called several times in my Page_Load?
Please see below my Page_Load how I call the Web Api:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var languages = Language.Enabled().OrderByDescending(x => x.IsDefault);
var selected = languages.Where(x => x.Code == HSESA.Library.Helpers.Context.PublicLanguage().Code).Select(x => x.Code).FirstOrDefault();
Test();
}
}
And here is the Test() method and how I initialized HttpClient:
private static HttpClient client = new HttpClient();
protected void Test()
{
string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
string FromUrl = HttpContext.Current.Request.Url.AbsoluteUri;
#region Old Code
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("Login", user));
postData.Add(new KeyValuePair<string, string>("FromUrl", FromUrl));
System.Net.Http.HttpContent content = new System.Net.Http.FormUrlEncodedContent(postData);
string url = "http://localhost:1899";
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsync("/api/login/checkLogin", content).Result;
if (response.IsSuccessStatusCode)
{
LoginItemViewModel data = null;
string responseString = response.Content.ReadAsStringAsync().Result;
Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(responseString);
data = Newtonsoft.Json.JsonConvert.DeserializeObject<LoginItemViewModel>(responseString);
}
#endregion
}
Thanks in advance to someone that can help me with my problem.

Related

How to call web api with multiple parameter in c# xamarin forms

I know this is a repeated question. I have tried many examples showed on stackoverflow. But the API is still not calling and it shows 404 not found error. I have tried the below examples,
Example 1:
using (var loginData = new MultipartFormDataContent())
{
loginData.Add(new StringContent(JsonConvert.SerializeObject(login.Email)), "emailId");
loginData.Add(new StringContent(JsonConvert.SerializeObject(this.Password)), "password");
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await httpClient.PostAsync("http://6cxsfera.ngrok.io/api/users/authenticate", loginData);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
Application.Current.MainPage = new AppShell();
}
}
Example 2:
JObject loginData = new JObject();
loginData.Add("emailId", login.Email);
loginData.Add("password", this.Password);
var httpClient = new HttpClient();
var httpContent = new StringContent(loginData.ToString(), Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("http://6cxsfera.ngrok.io/api/users/authenticate", httpContent);
My API:
[Route("authenticate")]
[HttpPost]
public HttpResponseMessage Login(HttpRequestMessage request, string emailId, string password)
{
}
Please suggest me to pass multiple parameters to web API in c# xamarin forms.
You can generate code by postman. Then check hat you are missing. you can even use same code generated by postman. https://learning.getpostman.com/docs/postman/sending_api_requests/generate_code_snippets/
just install restSharp nuget package.. it will work with postman generated code.
Instead of creating JObject create a class which holds your emailId and password property like below.
public class UserModel
{
public string emailId {get;set;}
public string password {get;set;}
}
now later instantiate UserModel and assign values like below
UserModel user = new UserModel
{
emailId = "emailId",
password = "password"
};
Serialize UserModel like below
string serializedModel = await Task.Run(() => JsonConvert.SerializeObject(user));
var contents = new StringContent(serializedModel);
contents.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
Make a Post Request
var response = await httpClient.PostAsync("http://6cxsfera.ngrok.io/api/users/authenticate", contents);
If the above solution doesn't work try changing your Web Api method route like below
Route["api/users/authenticate"]
Hope this will solve your issue... :)
you could try this:
using (var httpclient = new HttpClient())
{
var formcontent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("emailId",emailId),
new KeyValuePair<string, string>("password","password")
});
var request = await httpclient .PostAsync("http://6cxsfera.ngrok.io/api/users/authenticate", formcontent);
request.EnsureSuccessStatusCode();
var response = await request.Content.ReadAsStringAsync();
}

C# How to post data with multiple POST requests through Facebook API

I've been trying to post a message along with a link, I can send one POST request, but I am not sure how would one send two.
Here's my code:
private void Button2_Click(object sender, EventArgs e)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://graph.facebook.com");
string message = "hello";
string link = "www.facebook.com"
var payload = GetPayload(new {message});
HttpResponseMessage response2 = client.PostAsync($"me/feed?access_token={TextBox1.Text}", payload).Result;
}
}
private static StringContent GetPayload(object data)
{
var json = JsonConvert.SerializeObject(data);
return new StringContent(json, Encoding.UTF8, "application/json");
}
I am not sure how can I include the link too along with the message.
Al-right it turns out that the variable link should be passed as such:
var data = {message, link}
Thanks to chetan.

Xamarin Forms Post Request Http Issue

I'm working on making a POST request using my Xamarin form to send data to an Action in my controller in my WebAPI project. The code with breakpoints doesn't go beyond
client.BaseAddress = new Uri("192.168.79.119:10000");
I have namespace System.Net.Http and using System mentioned in the code.
private void BtnSubmitClicked(object sender, EventArgs eventArgs)
{
System.Threading.Tasks.Task<HttpResponseMessage> statCode = ResetPassword();
App.Log(string.Format("Status Code", statCode));
}
public async Task<HttpResponseMessage> ResetPassword()
{
ForgotPassword model = new ForgotPassword();
model.Email = Email.Text;
var client = new HttpClient();
client.BaseAddress = new Uri("192.168.79.119:10000");
var content = new StringContent(
JsonConvert.SerializeObject(new { Email = Email.Text }));
HttpResponseMessage response = await client.PostAsync("/api/api/Account/PasswordReset", content); //the Address is correct
return response;
}
Need a way to make a Post request to that Action and sending that String or the Model.Email as a parameter.
You need to use a proper Uri and also await the Task being returned from the called method.
private async void BtnSubmitClicked(object sender, EventArgs eventArgs) {
HttpResponseMessage response = await ResetPasswordAsync();
App.Log(string.Format("Status Code: {0}", response.StatusCode));
}
public Task<HttpResponseMessage> ResetPasswordAsync() {
var model = new ForgotPassword() {
Email = Email.Text
};
var client = new HttpClient();
client.BaseAddress = new Uri("http://192.168.79.119:10000");
var json = JsonConvert.SerializeObject(model);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var path = "api/api/Account/PasswordReset";
return client.PostAsync(path, content); //the Address is correct
}

Simplest way to call REST

I have call to REST service from jscript that works fine:
post('/MySite/myFunct', { ID:22 })
How to make this call from C# in most native c# way?
UPD:
I need HTTPS solution also.
UPD:
And I need to use cookies
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "ID", "22" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com", content);
var responseString = await response.Content.ReadAsStringAsync();
Old traditional way is using HttpClient / HttpWebRequest.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/api/Test/TestPostData");
request.Method = "POST";
SampleModel model = new SampleModel();
model.PostData = "Test";
request.ContentType = "application/json";
JavaScriptSerializer serializer = new JavaScriptSerializer();
using (var sw = new StreamWriter(request.GetRequestStream()))
{
string json = serializer.Serialize(model);
sw.Write(json);
sw.Flush();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Apart from this I prefer more Restclient /Restsharp from nuget.
A simple example of post request will be like this
using RestSharp;
using RestTest.Model;
private void button1_Click(object sender, EventArgs e)
{
var client = new RestClient();
var request = new RestRequest();
request.BaseUrl = "http://carma.org";
request.Action = "api/1.1/searchPlants";
request.AddParameter("location", 4338);
request.AddParameter("limit", 10);
request.AddParameter("color", "red");
request.AddParameter("format", "xml");
request.ResponseFormat = ResponseFormat.Xml;
var plants = client.Execute<PowerPlantsDTO>(request);
MessageBox.Show(plants.Count.ToString());
}
You can use HTTP Verbs directly from call
A Post example:
public void Create(Product product)
{
var request = new RestRequest("Products", Method.POST); < ----- Use Method.PUT for update
request.AddJsonBody(product);
client.Execute(request);
}
A Delete Example
public void Delete(int id)
{
var request = new RestRequest("Products/" + id, Method.DELETE);
client.Execute(request);
}
For adding header in request
request.AddHeader("data", "test");
A Get Request
private RestClient client = new RestClient("http://localhost:8080/api/");
RestRequest request = new RestRequest("Products", Method.GET);
RestResponse<YourDataModel> response = client.Execute<YourDataModel>(request);
var name = response.Data.Name;

Twilio REST Api call bad request

I've implemented Twilio REST API with C# successfully earlier. However, all of a sudden the API calls that are made keep getting 400 - BAD REQUEST.
The response body doesn't contain any specific error either...
I'll say it again, it worked for a week or two and all of sudden it returns BAD REQUEST.
The code is exact the following below.
public async Task SendSmsAsync(string number, string message)
{
var accountSid = _configuration["Authentication:Twilio:AccountSID"];
var authToken = _configuration["Authentication:Twilio:AuthToken"];
var twilioNumber = _configuration["Authentication:Twilio:Number"];
var credentials = new NetworkCredential(accountSid, authToken);
var handler = new HttpClientHandler { Credentials = credentials };
using (var client = new HttpClient(handler))
{
var url = $"https://api.twilio.com/2010-04-01/Accounts/{ accountSid }/Messages";
var body = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("To", number),
new KeyValuePair<string, string>("From", twilioNumber),
new KeyValuePair<string, string>("Body", message),
};
var content = new FormUrlEncodedContent(body);
content.Headers.ContentType.CharSet = "UTF-8";
var response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
//Uri success = response.Headers.Location;
}
}
}

Categories