Error Calling a Odata service in C# - c#

I am trying to call a Odata service from the C# application. I have called the rest services before and consumed the responses in the C#, and trying Odata for the first time. Below is the Code I am using
using (var client = new HttpClient())
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
Uri uri = new Uri(BaseURL);
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var response = client.GetAsync(uri).Result;
var responsedata = await response.Content.ReadAsStringAsync();
I am using the same URL and the credentials in PostMan and it returns the response. But throws error i the code, is there something different we need to follow calling a Odata services.Please help with this

It is recommended to use a library to access OData. There are at least a couple of libraries that you can choose from, such as:
https://www.nuget.org/packages/Microsoft.OData.Client/ (OData v4)
https://www.nuget.org/packages/Microsoft.Data.OData/ (OData v1..3)

Related

While HttpClient gives bad gateway error, Postman works well for same rest endpoint

I have a problem about 502 gateway error in my production server.
I try to develop an application which calls azure rest endpoints. I get response with Postman by sending the endpoint which has following documentation:
https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/classification-nodes/get?view=azure-devops-rest-6.0
While Postman or Invoke-RestMethod work well with azure endpoint, but API, developed by me, based on HttpClient/RestSharp give an 502 Bad gateway error. HttpClient code part can be found below:
var personalaccesstoken = "<my-token>";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "<my-email-address>", personalaccesstoken))));
HttpRequestMessage requestMessage = new HttpRequestMessage();
requestMessage.Method = HttpMethod.Get;
requestMessage.RequestUri = new Uri("<my-azure-server-address>/_apis/wit/classificationNodes/Areas?$depth=100");
using (HttpResponseMessage response = client.SendAsync(requestMessage).Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
return responseBody;
}
}
How can I solve the problem or which tool can I use to find the exact problem?
Thank you in advance:

HttpClient Post Async call

I am trying to call a Windchill Odata rest service. THE HTTP GET method works fine, but it is not working as expected when making a POST request. I am also not sure how to pass the required parameter to the URL. Any suggestions will help a lot.
URL that I am trying to call
http://Hostname/Windchill/servlet/odata/v3/ProdMgmt/Parts('OR:wt.part.WTPart:123456')/PTC.ProdMgmt.GetPartStructure?$expand=Components($select=PartName,PartNumber;$expand=PartUse($select=FindNumber,LineNumber,Quantity,Unit);$levels=1)
Parameter that need to be passed to the URL is ('OR:wt.part.WTPart:123456'). I am doing this in C# .NET.
My C# code
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
var byteArray = Encoding.ASCII.GetBytes("abc:defg!");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
client.DefaultRequestHeaders.Add("CSRF_NONCE", a.NonceValue);
var message = await client.PostAsync("hostname/Windchill/servlet/odata/v3/ProdMgmt/Parts('OR:wt.part.WTPart:123456')/PTC.ProdMgmt.GetPartStructure?$expand=Components($select=PartName,PartNumber;$expand=PartUse($select=FindNumber,LineNumber,Quantity,Unit);$levels=1)", null);
}
Any example or sample code is much appreciated.

Getting Web Service data without using Async

There is this webservice, which i need to get some information. This webservice has an Authentication Header, and two parameters embedded in the body of the request. I have wrote the method using HttpClient class:
HttpClient httpClient = new HttpClient();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpRequestMessage request = new HttpRequestMessage();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
request.RequestUri = new Uri("URL");
request.Method = HttpMethod.Post;
request.Headers.Add("AUTHENTICATION_Key", "AUTHENTICATION_VALUE");
request.Content = new StringContent("{\"P1\":\"V1\",\"P2\":\"V2\"}",Encoding.UTF8,"application/json");
HttpResponseMessage response = await httpClient.SendAsync(request);
if (response.StatusCode == HttpStatusCode.OK)
{
var responseString = await response.Content.ReadAsStringAsync();
}
the problem has risen from where the project I need to use, is using DotNet 2.0 and in .Net 2 we cannot use asynchronize therefore I cannot use await and SendAsync() as well as ReadAsStringAsync() another problem is SecurityProtocolType.Tls12 is not available in .Net 2. and Im going to need it to get data from it.
I appriciate the help.

.net core console app calling PHP rest API with basic authentication

I am not able to get the data from a php rest api from the .net core console app(the call works fine from POSTMAN). I use below code for basic authentication and looks like it redirects to https://www.thesite.org/login for HttpClient.
Not sure what I am missing.
static async Task<RootObject> GetOrderDataAsync()
{
HttpClient client = new HttpClient();
RootObject result = null;
var byteArray = Encoding.ASCII.GetBytes("username:password");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
client.BaseAddress = new Uri("https://www.thesite.org/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("orders/processing");
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsAsync<RootObject>();
}
return result;
}
I think when you use AuthenticationHeaderValue you don't need to explicitly convert to a Base64 string. Have you tried:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "username:password");

JFROG Repository Creation with Api

Hi I want to create Repository with Artifactory JFROG Api,But I got 406 error code with api
I can run this json request over postman with selected application/json mime type
But I cant run over my c# code.What should I do in my .net code to use jfrog artifactory api?
{"key":"ArtifactRepoGroup3","rclass":"virtual","packageType":"nuget","description":"This repo created by"}
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(BaseAddress);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
............
HttpResponseMessage response = client.PutAsJsonAsync(puturi,
value).Result; }
I cant run PutAsJsonAsync method with standart application/json but I can do it use StringContent and embedded jfrog specific mime type into my content
VirtualRepository repository = new VirtualRepository();
repository.key = "ArtifactRepoGroup1";
repository.packageType = "nuget";
repository.rclass = "virtual";
repository.description = "This repo created by ";
var content = JsonConvert.SerializeObject(repository);
var conent = new StringContent(content, Encoding.UTF8,
"application/vnd.org.jfrog.artifactory.repositories.VirtualRepositoryConfiguration+json");
....
var response = client.PutAsync(uri, conent).Result;
string b = response.Content.ReadAsStringAsync().Result;

Categories

Resources