In a Xamarin Form app, from the Master Page menu, in the Portable project, I call Content page InfoScreen into the Detail. InfoScreen code looks something like this:
public InfoScreen()
{
InitializeComponent();
ListAccounts();
}
public void ListAccounts()
{
SearchAccounts SA = new SearchAccounts();
SearchAccountRequest searchAccountRequest = new SearchAccountRequest("000123456789", "","","","");
var searchAccountResult = SA.SearchAccountAsync(searchAccountRequest);
}
Notice that on load it calls ListAccounts, located in a class in the Portable project, which looks as follows:
public async Task<SearchAccountResult> SearchAccountAsync(SearchAccountRequest searchAccountRequest)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:00/api/");
string jsonData = JsonConvert.SerializeObject(searchAccountRequest);
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = await client.PostAsync("SearchForAccount", content);
var result = response.Content.ReadAsStringAsync().Result;
if (result != "")
{
var sessionResponseJson = JsonConvert.DeserializeObject<SearchAccountResult>(result);
}
However, when var response = await client.PostAsync("SearchForAccount", content); gets hit, it just goes back to InfoScreen and continues to load. The API is never hit, which I'm running locally on debug mode. I tested with Postman and it's working correctly.
I also tried:
var client = new HttpClient();
var data = JsonConvert.SerializeObject(searchAccountRequest);
var content = new StringContent(data, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://localhost:00/api/SearchForAccount", content);
if (response.IsSuccessStatusCode)
{
var result = JsonConvert.DeserializeObject<SearchAccountResult>(response.Content.ReadAsStringAsync().Result);
}
else
{
//
}
Same results. What am I missing?
Thanks
===============
Tried calling the DEV server, utilizing IP, works fine from Postman. Only thing I'm getting in the app is
Id = 1, Status = WaitingForActivation, Method = {null}
Related
I am using a library for communicate with a crypto api.
In Console Application every thing is ok about async post.
But in webforms it goes to sleep and nothing happens!
Just loading mode.
Here is the method :
private async Task<WebCallResult<T>> PostAsync<T>(string url, object obj = null, CancellationToken cancellationToken = default(CancellationToken))
{
using (var client = GetHttpClient())
{
var data = JsonConvert.SerializeObject(obj ?? new object());
var response = await client.PostAsync($"{url}", new StringContent(data, Encoding.UTF8, "application/json"), cancellationToken);
var content = await response.Content.ReadAsStringAsync();
// Return
return this.EvaluateResponse<T>(response, content);
}
}
private HttpClient GetHttpClient()
{
var handler = new HttpClientHandler()
{
AllowAutoRedirect = false
};
var client = new HttpClient(handler);
client.BaseAddress = new Uri(this.EndpointUrl);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
In line var response = web site goes to loading mode.
No error - Nothing - Just Loading.
How can i fix this problem in webforms?
In Console Application it is working fine.
Maybe i should change something in Web.config!!!
Here is the library
I've been troubleshooting this for days now but still no luck.
I'm trying to send parameters to an API link provided by Microsoft O365 Power Automate, this API requires a customer number, company code, and posting date and in return, it will send me a table with the list of items that have the same customer number, company code, and posting date. When I'm doing testing in Postman the sends status code 200, but when using VS and my code it always returns a status code 400.
SoaController.cs
[HttpPost]
public async Task<IActionResult> Index(string company, string customer, string asof)
{
using (var client = new HttpClient())
{
SoaParams soaParams = new SoaParams
{
Posting_Date = asof,
Company_Code = company,
Customer_Number = customer
};
var SoaJson = JsonConvert.SerializeObject(soaParams);
var buffer = Encoding.UTF8.GetBytes(SoaJson);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.BaseAddress = new Uri(SD.ApiUri);
var response = await client.PostAsync(SD.ApiUri, byteContent);
if (response.IsSuccessStatusCode)
{
return RedirectToAction(nameof(Success), Json(response));
}
else
{
return RedirectToAction(nameof(Failed), Json(response));
}
}
}
The below image shows that the parameters needed are correct.
But it's SuccessStatusCode always returns false
I use a code provided by PostMan that look like this:
public List<BapiOpenItemDto> GetResponse(SoaParams soaParams, string uri)
{
var SoaJson = JsonConvert.SerializeObject(soaParams);
var client = new RestClient(uri);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "[\r\n" + SoaJson + "\r\n]\r\n", ParameterType.RequestBody);
IRestResponse<List<BapiOpenItemDto>> response = client.Execute<List<BapiOpenItemDto>>(request);
return response.Data;
}
and its working now.
I'm having a problem while developing my api, i have some calls, like CreateUser, DeleteUser, GetAllUser etc. and no matter what, i cannot make consecutives create and delete user calls.
When i call the create user method, returning the user id, i cannot delete the newly created user, it will return a 404 not found status code.
I've tried with postman, using the runner collection, and it gives no errors, it works fine, so i think it's a problem with my api calls, and not with my controller method.
I've also tried to create a little console app for test (attached), following the example on the microsoft documentation, with no luck,
At this point i'm not sure what may be the problem, i tought about an sql problem, maybe it doesn't have time to create the row, before i delete it, but in postman works fine, so... , or maybe a problem with async calls, but i always wait for result, so i think it's fine.
static string _basicAuthenticationUser = "UserTest";
static string _basicAuthenticationPassword = "Password";
static string _email = "user#gmail.com";
static string _password = "test";
static UtentiApiModel userToCreate =
new UtentiApiModel
{
Nome = "Alex",
Cognome = "Hello",
Email = "user#gmail.com",
Password = "test",
};
static HttpClient client = new HttpClient();
static void Main(string[] args)
{
var authValue = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_basicAuthenticationUser}:{_basicAuthenticationPassword}")));
client = new HttpClient()
{
DefaultRequestHeaders = { Authorization = authValue }
};
RunAsync().GetAwaiter().GetResult();
}
private static async Task RunAsync()
{
client.BaseAddress = new Uri("http://localhost:1045/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var id = await CreateUserAsync(userToCreate);
var statusCode = await DeleteUserAsync(id);
Console.WriteLine(statusCode.ToString());
Console.ReadKey();
}
static async Task<long> CreateUserAsync(UtentiApiModel utente)
{
var json = JsonConvert.SerializeObject(utente);
var content = new StringContent(json.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(
"test/", content);
response.EnsureSuccessStatusCode();
var reslt = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<UtentiApiModel>(reslt).Id;
}
static async Task<HttpStatusCode> DeleteUserAsync(long id)
{
HttpResponseMessage response = await client.DeleteAsync(
"/test/"+id+");
return response.StatusCode;
}
Heres the code to my HttpPost request
async void ContinueBtn_Clicked(object sender, EventArgs e)
{
if (!CheckValidation())
{
LoginBLL cust = new LoginBLL();
EncryptPassword encrypt = new EncryptPassword();
cust.name = txtFieldName.Text;
cust.email = txtFieldEmail.Text;
cust.Password = encrypt.HashPassword(txtFieldPass.Text);
cust.profession = txtFieldJob.Text;
cust.company = txtFieldCompany.Text;
cust.subId = 1320;
HttpClient client = new HttpClient();
string url = "https://www.example.com/api/customer/";
var uri = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
var json = JsonConvert.SerializeObject(cust);
var content = new StringContent(json, Encoding.UTF8, "application/json");
response = await client.PostAsync(uri, content);
if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
{
validationName.Text = await response.Content.ReadAsStringAsync();
}
else
{
validationName.Text = await response.Content.ReadAsStringAsync();
}
}
And I am getting this error when I am executing the above function
No HTTP resource was found that matches the request URI 'https://www.example.com/api/customer/'.
But it is working fine in Postman with same variables.
I even verified the JSON generated in POSTMAN with the JSON being generated in the Visual Studio it is identical.
I am running this on iphone 8 iOS 12.0
I'm learning how to create WEB-API client
I've created some simple API:
[HttpGet]
public IHttpActionResult GetInfo()
{
return Ok("Its working!");
}
[HttpPost]
public IHttpActionResult PostInfo(ClientDataDto dto)
{
try
{
someMethod(dto.IdKlienta, dto.Haslo, dto.IdZgloszenia, dto.HardwareInfo, dto.SoftwareInfo);
return Ok("sent");
}
catch
{
return BadRequest();
}
}
For now I just trying to call GET method.
When I use Fiddler with addr
localhost:someport/api/Client2
its working
but when i try to do it by client, which code is below:
private static HttpClient client = new HttpClient();
static void Main(string[] args)
{
#region TESTONLY
var debug = new XMLData();
string HardwareInfoXML = debug.HardwareXML;
string SoftInfoXML = debug.SoftwareXML;
int id_zgloszenia = 20;
int idKlienta = 25;
//haslo = "202cb962ac59075b964b07152d234b70";
#endregion
var data = new ClientDataDto() { HardwareInfo = HardwareInfoXML, SoftwareInfo = SoftInfoXML, IdKlienta = idKlienta, IdZgloszenia = id_zgloszenia };
RunAsync(data);
}
private static async Task RunAsync(ClientDataDto data)
{
var stringContent = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri(#"http://localhost:7774/api/client2/");
var url = new Uri(#"http://localhost:7774/api/client2/");
var res1 = await client.GetAsync(url);
var res = await client.PostAsync(url, stringContent);
res.EnsureSuccessStatusCode();
}
Application closing without any info at
var res1 = await client.GetAsync(url);
I have checked to see all exceptions in Debug exception Windows, but it is just closing after trying call GetAsync
PostASync doesn't work too.
What is wrong here?
i'm really sorry that i've posted simpe problem.
sulotion is to add .Wait() on RunAsync(data);
RunAsync(data).Wait();