Strange response from Asp.Net Web Api Post - c#

I have a Asp.Net Web Api like the following
public async Task<IHttpActionResult> Post(Guid id, OrganisationModel model)
{
try
{
_orgService.AddNewOrganisationToParent(newOrg, org);
await Context.SaveChangesAsync();
return Ok(newOrg.Id);
}
catch (Exception ex)
{
Log.ErrorFormat("Problem creating new organisation {0}. Error {1}", UserId, ex);
return InternalServerError(ex);
}
}
When I call this from another Asp.Net Web application with the following;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var newOrg = Newtonsoft.Json.JsonConvert.SerializeObject(new
{
name = systemTree.Name,
type = 0
});
var content = new StringContent(newOrg.ToString(), Encoding.UTF8, "application/json");
var newOrgId = Guid.Empty;
using (var response = await client.PostAsJsonAsync(orgEndpoint + orgId, content))
{
response.EnsureSuccessStatusCode();
newOrgId = response.Content.ReadAsAsync<Guid>().Result;
}
The response is rather strange, the code shown throws and exception "exceptionMessage": "Unable to translate bytes [B4] at index 3 from specified code page to Unicode.",
If I read this as a string I get the following
"SJN4OMN4��MIK2�M574Ե0H6�500H1NL2J�4IR\u0002\0"
Is there something I am missing? Thanks in advance.

Related

500 Error when calling an API in C# with having ID in URL

I need to Call a API using C# to this URL: I changed the URL so not working here but it is working in postman)
https://uattest.com/api/leads/28/comments
This is the object to post:
{
"code":"22535345454-263663",
"text":"This is a test"
}
This is working fine when I post via postman, but when I post using my C# code I am getting 500 error. This is my C# code:
Controller:
[HttpPost]
[Route("AddNote")]
public Task<NoteReturnModel> AddNote(int LeadId, Comments note)
{
return Repository.AddNote(LeadId, note);
}
Repository
public async Task<NoteReturnModel> AddNote(int LeadId, Comments note)
{
using (GetWSObject<NoteReturnModel> addObjectInt = new GetWSObject<NoteReturnModel>())
{
string URL = string.Format("/api/leads/" + LeadId+ "/comments");
return await addObjectInt.PostWSObjectModel(URL, note);
}
}
and this is PostWSObjectModel Method:
public async Task<T> PostWSObjectModel(string uriActionString, Object model)
{
T returnValue = default(T);
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(WebConfigurationManager.AppSettings["URL"]);
var content = new StringContent(JsonConvert.SerializeObject(model));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = await client.PostAsync(uriActionString, content);
response.EnsureSuccessStatusCode();
returnValue = JsonConvert.DeserializeObject<T>(((HttpResponseMessage)response).Content.ReadAsStringAsync().Result);
}
return returnValue;
}
catch (Exception e)
{
throw (e);
}
}
I am checking all the URLs are correct, in this line that calling HttpResponseMessage response = await client.PostAsync(uriActionString, content); giving error.

Values of BsonDocument missing when PutAsync over web request?

I am trying to send a simple BsonDocument to WebAPI through PutAsync request.
However, the values of the BsonDocument missing when passed to the WebAPI Controller.
Here are the codes of my client.
public static async Task<HttpResponseMessage> sendBdoc()
{
try
{
var abc = new BsonDocument("Abc","hoho");
var bformatter = new BsonMediaTypeFormatter();
var id = ObjectId.GenerateNewId();
HttpClient client = new HttpClient()
client.BaseAddress = new Uri("http://localhost:58836");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
var response = await client.PutAsync($"api/query/{id}", abc, bformatter);
return response;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
Here are the codes of my controller:
public async Task<IHttpActionResult> Put(string id, BsonDocument doc)
{
try
{
//MongoDB Connection stuff here
var filter = new BsonDocument("_id", ObjectId.Parse(id));
var update = collection.ReplaceOneAsync(filter, doc, new UpdateOptions() { IsUpsert = true });
var result = await update;
if (result.IsAcknowledged)
{
return Ok();
}
return NotFound();
}
catch (Exception e)
{
return InternalServerError();
}
}
Screenshot of debugging my client app, variable abc is filled with value.
https://i.stack.imgur.com/txp8l.png
Screenshot of debugging at web controller side, value of the BsonDocument turned null now.
https://i.stack.imgur.com/lBTe3.png
Do i overlook something? Thanks alot
It could be a limitation of the default model binder.
Could you try to remove the "string id" from the Put method and resend the request?

Xamarin.Forms HTTP Post to Web Service - 404 Error

Sorry if this question has been asked already but I can not seem to find one that relates to my issue. I have a web service built using C# Asp.Net Web API, here I have the following POST method:
[HttpPost]
[Route("AddLocation")]
public void PostLocation(Locations model)
{
using (Entities db = new Entities())
{
C_btblFALocation newLocation = new C_btblFALocation()
{
cLocationCode = model.Code,
cLocationDesc = model.Description
};
db.C_btblFALocation.Add(newLocation);
db.SaveChanges();
}
}
In my Xamarin.Forms project I have my Rest Service Class:
public async Task SaveLocationAsync(Locations item)
{
var uri = new Uri(string.Format(Constants.LocationSaveRestUrl));
try
{
var json = JsonConvert.SerializeObject(item);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await client.PostAsync(uri, content);
if (response.IsSuccessStatusCode)
{
Debug.WriteLine(#" Location successfully added.");
}
else
{
Debug.WriteLine(#" Oops, there seems to be a problem.");
}
}
catch (Exception ex)
{
Debug.WriteLine(#" ERROR {0}", ex.Message);
}
}
And my URL is set in my Constants class:
public static string LocationSaveRestUrl = "http://172.16.124.18/ArceusService/api/Assets/AddLocation/";
The problem is I keep getting a 404 error. I have tried every way I can think of to set the URL but no luck. The data seems to be passed through fine from debugging but I don't know how the URL should be for a POST method?
Thanks for any help!
How is your client variable declared? Usually you set a BaseAddress and in your Get/PostAsync you only set the actual resource URI.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://something.com/api/");
var response = await client.GetAsync("resource/7");
}

How can I use the access token to get a list of projects from a website in c#?

I am trying to create a C# console application to download project details from a website which supports REST OAuth 2.0. How do I make a request/response call to the website using the Access Token?
Here is my code:
public string token = "4bjskfa2-b37d-6244-8413-3358b18c91b6";
public async Task GetProjectsAsync()
{
try
{
HttpClient client = new HttpClient();
var projects = "https://app.rakenapp.com/api/v2/projects?" + token;
client.CancelPendingRequests();
HttpResponseMessage output = await client.GetAsync(projects);
if (output.IsSuccessStatusCode)
{
string response = await output.Content.ReadAsStringAsync();
project proj = JsonConvert.DeserializeObject<project>(response);
if (proj != null)
{
Console.WriteLine(proj.name); // You will get the projects here.
}
}
}
catch (Exception ex)
{
//catching the exception
}
}
you need to add a header to your request:
string url = "https://app.rakenapp.com/api/v2/projects";
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authorizationToken);
HttpResponseMessage response = await httpClient.GetAsync(url);
var contents = await response.Content.ReadAsStringAsync();
var model = JsonConvert.DeserializeObject<project>.contents);
return model;
}

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