StatusCode: 405, ReasonPhrase: 'Method Not Allowed' while using POST METHOD - c#

I keep getting this error when trying to use POST Method.
I need to get from the API a list of certificates into a LIST, I know that "lista" is null right now, since I canĀ“t get the API to bring me the lists yet.
public async Task<List<Certificaciones>> grillaCertificadosAsync(int id)
{
List<Certificaciones> lista = new List<Certificaciones>();
var cert = new jsonCert()
{
idProyecto = id
};
var id1 = JsonConvert.SerializeObject(cert);
var content = new StringContent(id1, Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var result = await client.PostAsync("https://certificacionesbuho.mendoza.gov.ar/api/BuhoBlanco/GetInfoCert", content);
var responseBody = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
return lista;
This is the API.
[Route("Api/BuhoBlanco/GetInfoCert")]
[System.Web.Http.ActionName("GetInfoCert")]
[System.Web.Http.HttpPost]
public Respuesta GetInfoCert([FromBody]infoCertRequest infoCert)
{
Respuesta rta = new Respuesta();
try
{
BuhoServicio.ServicioBuhoBlanco _servicio = new BuhoServicio.ServicioBuhoBlanco();
rta.Exito = true;
rta.StatusCode = HttpStatusCode.OK;
rta.Data = _servicio.infoCertificados(infoCert.idProyecto);
//((IDisposable)_servicio).Dispose();
return rta;
}
catch (Exception ex)
{
rta.Error = ex.Message;
rta.Exito = false;
rta.StatusCode = HttpStatusCode.InternalServerError;
return rta;
}
}

IMHO route should be like this
[HttpPost("~/Api/BuhoBlanco/GetInfoCert")]
public Respuesta GetInfoCert([FromBody]infoCertRequest infoCert)

Related

HttpClient.PostAsJsonAsync crushed without exception

I am trying to call an api(POST method) with HttpClient.PostAsJsonAsync. However, it stopped at httpClient.PostAsJsonAsync without any exception.
The source code as below:
public static async Task<oResult> PostApi(string JSON_sObject, string sEnd_Url) {
oResult oResult = new oResult();
var Data = JsonConvert.DeserializeObject(JSON_sObject);
var Url = "http://localhost:44340/" + sEnd_Url;
HttpClient httpClient = new HttpClient();
try {
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await httpClient.PostAsJsonAsync(new Uri(Url), Data); // it stopped here
if (response.IsSuccessStatusCode)
{
var sResponse_content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<oResult>(sResponse_content);
}
else
{
return oResult;
}
}
catch (Exception ex)
{
LogFile(ex);
return oResult;
}
}
Please advice me if any issue from the source code.
Thank you
you should not trying serialize deserialize twice
remove from your code
var Data = JsonConvert.DeserializeObject(JSON_sObject);
and replace
HttpResponseMessage response = await httpClient.PostAsJsonAsync(new Uri(Url), Data);
with this
var content = new StringContent(JSON_sObject, Encoding.UTF8, "application/json");
var response = await client.PostAsync(sEnd_Url, content);
also fix base httpclient address
var baseUri= #"http://localhost:44340";
using HttpClient client = new HttpClient { BaseAddress = new Uri(baseUri) };
try {

C# GetAsync await returns Status code 204 Whereas PostMan returns 200

I have a Get API call to WebAPI using GetAsync method that fetches some values in JSON based on a location parameter. I am running the WebAPI call in a loop and for some reason, for certain Location parameters, the code returns "No content" status code 204. When I call the webAPI from Postman, it returns the data successfully.
Here is my code:
private static async Task<string[]> GetLatLongValues(string locationDescription)
{
string[] latLng = new string[2];
string locationAPI = "https://zoek-search-api-live-us-2.azurewebsites.net/" ;
try
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(locationAPI);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("cache-control", "no-cache");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//HTTP GET
var responseTask = await client.GetAsync("Geocode/SearchLocation?location=" + Uri.EscapeDataString(locationDescription)); //.ConfigureAwait(continueOnCapturedContext: false);
responseTask.EnsureSuccessStatusCode();
if (responseTask.IsSuccessStatusCode)
{
var resString = await responseTask.Content.ReadAsStringAsync ();
//resString.Wait();
if (resString.Length !=0)
{
Newtonsoft.Json.Linq.JArray resArr = Newtonsoft.Json.Linq.JArray.Parse(resString);
latLng[0] = resArr[0]["latitude"].ToString();
latLng[1] = resArr[0]["longitude"].ToString();
validLatLong.Add(locationDescription, latLng);
}
else
{
latLng[0] = "0";
latLng[1] = "0";
InvalidLatLong.Add(locationDescription, latLng);
isLocValid = false;
}
}
}
return latLng;
}
catch(Exception ex)
{
latLng[0] = "0.0";
latLng[1] = "0.0";
return latLng;
}
}

Xamarin PostAsync giving No Content Resposne

I am doing this function in Xamarin Forms:
public async Task<HttpResponseMessage> RegisterClient(string url)
{
try
{
using (HttpClient httpclient1 = new HttpClient())
{
var newClient = new Client()
{
CountryId = 223,
Email = "somename#123.com",
Fname = "From Xamarin",
UserName = "somename",
Dob = Convert.ToDateTime("2020-01-01"),
Password = "SomeSome"
};
var jsonObject = JsonConvert.SerializeObject(newClient);
HttpContent content = new StringContent(jsonObject, Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpclient1.PostAsync(url, content);
return response;
}
}
catch (Exception ex)
{
await DisplayAlert("Information", ex.Message, "Ok");
return null;
}
}
This code function is returning No Content even after assigning values. Any clue where i am wrong. WebAPI is working fine in POSTMAN. My WebAPI Controller looks like this:
[HttpPost("PostClient")]
public async Task<ActionResult<Client>> PostClient(Client client)
{
try
{
_context.Clients.Add(client);
await _context.SaveChangesAsync();
return CreatedAtAction("GetClient", new { id = client.ClientId }, client);
}
catch(Exception ex)
{
return null;
}
}
Please help. Thank you
Resolved.
HttpClient httpClient = new HttpClient();
Uri uri = new Uri(url);
StringContent content = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri, content);
httpResponseMessage.EnsureSuccessStatusCode();
var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
Console.WriteLine(httpResponseBody);
Replaced Encoding.UTF8 to UnicodeEncoding.UTF8 and it worked. Mystery solved.

Xamarin Sending POST Data

I am attempting to send POST data to my server and get back a response. For some reason, no POST data is actually getting sent. A request is being sent to my server but the POST array is empty.
Here is my code for sending the request:
public class GlobalMethods
{
public async Task<string> callAjax(string mthd,NameValueCollection parameters)
{
var client = new HttpClient();
var content = JsonConvert.SerializeObject(parameters);
var result = await client.PostAsync("http://dev.adex-intl.com/adex/mvc/receiving/"+mthd, new StringContent(content)).ConfigureAwait(false);
var tokenJson = "";
if (result.IsSuccessStatusCode)
{
tokenJson = await result.Content.ReadAsStringAsync();
}
return tokenJson;
}
}
And here is my code that calls the above method:
public void loginPressed(object sender, EventArgs e)
{
if(String.IsNullOrEmpty(badge.Text)) {
DisplayAlert("Error", "Enter your badge number", "Ok");
} else {
IsBusy = true;
NameValueCollection parameters = new NameValueCollection();
parameters["badgetNumber"] = badge.Text;
GlobalMethods globalMethods = new GlobalMethods();
var results = globalMethods.callAjax("login", parameters);
}
}
I'm not sure what I'm doing wrong. Also, I'm a newbie to Xamarin and C# so I'm not even sure if the way I am attempting to do things is the best way.
You haven't specify the type of content that you want to send, in your case it's 'application/json', you can set it like that:
"var client = new HttpClient();
var content = new StringContent(JsonConvert.SerializeObject(parameters));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");". Also, I would suggest you to write code like that:
var uri = new Uri(url);
using (var body = new StringContent(JsonConvert.SerializeObject(data)))
{
body.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var request = new HttpRequestMessage
{
Version = new Version(1, 0),
Content = body,
Method = HttpMethod.Post,
RequestUri = uri
};
try
{
using (var response = await _client.SendAsync(request,cancellationToken))
{
if (response.IsSuccessStatusCode)
{
//Deal with success response
}
else
{
//Deal with non-success response
}
}
}
catch(Exception ex)
{
//Deal with exception.
}
}
You can use PostAsync for async sending data to server. your code should be something like this:
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "p1", "data1" },
{ "p2", "data2" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/index.php", content);
var responseString = await response.Content.ReadAsStringAsync();

asp.net core httpclient ArgumentNullException

I'm trying to make a POST request using HttpClient but it keeps throwing an ArgumentNullException.
on this call var response = await client.PostAsync(url, content);
I've set break points and verified that the values are populated.
Is there something I'm missing that would cause this?
public async Task<bool> PostSomeObject()
{
var transaction = new CreateTransactionRequest();
transaction.MerchantAuthentication.Name = "notmyName";
transaction.MerchantAuthentication.TransactionKey = "notMyKey";
transaction.TransactionRequest.TransactionType = "authOnlyTransaction";
transaction.TransactionRequest.Amount = 5;
transaction.TransactionRequest.Payment.CardCode = "999";
transaction.TransactionRequest.Payment.CardNumber = "5424000000000015";
transaction.TransactionRequest.Payment.ExpirationMonth = 12;
transaction.TransactionRequest.Payment.ExpirationYear = 20;
var url = "xml/v1/request.api";
using (HttpClient client = new HttpClient())
{
var sampleClassObjectJson = JsonConvert.SerializeObject(transaction);
client.BaseAddress = new Uri("http://localhost:56858/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(sampleClassObjectJson, Encoding.UTF8, "application/json");
//throws NullException on this call here
var response = await client.PostAsync(url, content);
if (response.StatusCode == HttpStatusCode.OK)
return true;
else
throw new WebException("An error has occurred while calling PostSomeObject method: " + response.Content);
}
}
Based on a comment I've added a try catch for the ArgumentNullException
try {
var response = await client.PostAsync(url, content);
}
catch (System.ArgumentNullException ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
It's not stepping into the catch statement but in the Output from debug it throws the exception.
Here is the controller action that calls my Post method
public async Task<IActionResult> PaymentInformation(Payment paymentInfo)
{
var cookie = GetCheckoutCookie();
//if there isn't a cookie ID something went wrong, redirect to Index
if (cookie.ID == null)
{
return RedirectToAction("Index");
}
var cookieSession = CheckoutSession.getCheckoutSession(cookie.ID);
if (ModelState.IsValid)
{
var status = await PostSomeObject();
}
else
{
}
return PartialView();
}

Categories

Resources