Unable to consume OpenShift REST API in C#.net - api

I want to know how can I consume OpenShift Rest API into C#.net based application. I have gone through URL
https://access.redhat.com/documentation/en-US/OpenShift_Online/2.0/pdf/REST_API_Guide/OpenShift_Online-2.0-REST_API_Guide-en-US.pdf, in this there mentioned example for Ruby, Python and cRUL. but not mentioned for .Net. so I have created sample application for consuming this api.
below is the code -
string URL = "https://openshift.redhat.com/broker/rest/api";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/xml;";
try
{
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
Console.Out.WriteLine(response);
responseReader.Close();
}
catch (Exception e)
{
Console.Out.WriteLine("-----------------");
Console.Out.WriteLine(e.Message);
}
While executing above code I am getting following error -
"The remote server returned an error: (406) Not Acceptable."
Please let me where I am doing wrong.
Thanks in advance
Jyoti

You are using the wrong HTTP header. ContentType is used for POST/PUT operations to tell server what to expect. When you GET a resource you must specify an Accept header.
request.Accept = "application/xml";

Related

Post request error when sending "application/octet-stream" to an ASP.NET Core Web API service

I need to create an ASP.NET Core 3 Web API that understand this URL
http://myapp.com/MyASPNetCore3WebApi/myController/myWebMethod?user=A0001
and one zipfile which goes as a content. This is the code that calls the needed API, which I need to create:
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URI);
httpWebRequest.Timeout = -1;
httpWebRequest.KeepAlive = false;
httpWebRequest.Method = "POST";
httpWebRequest.ProtocolVersion = HttpVersion.Version10;
httpWebRequest.ContentType = "application/octet-stream";
httpWebRequest.Accept = "application/octet-stream";
httpWebRequest.ContentLength = data.Length;
Stream requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
The code above is working fine, it is used everyday, sending data to a java web service, now I am replacing that system for a new one in ASP.NET Core and I can't change the caller's code, that's why I need to create a Web API that understand that URL.
I have wrote this code in my Web API, but I guess I am missing something that I canĀ“t figure it out because I get an error ion the client (code above)
[HttpPost("myWebMethod")]
public FileStreamResult myWebMethod(string user, [FromBody] Stream compress)
{
byte[] zip = ((MemoryStream)compress).ToArray();
byte[] data = ZipHelper.Uncompress(zip);
.....................
}
The error I get in the client is this:-
[System.Net.WebException] {"The remote server returned an error: (415)
Unsupported Media Type."} System.Net.WebException
Thanks in advance for any help
If the goal is to read the raw request content, this can be done using HttpContext controller property. HttpContext has Request property that provides access to the actual HTTP request.
No additional model properties or controller arguments are needed to access raw request stream. It's important to note that FromBody and FromForm binding should not be used in this case.
There are couple notes regarding the code in the example from the original question.
byte[] zip = ((MemoryStream)compress).ToArray();
byte[] data = ZipHelper.Uncompress(zip);
The HttpContext.Request.Body property does not return MemoryStream, it returns its own implementation of a Stream. It means that there is no ToArray method.
When reading the entire content of a request directly into the server's memory, it is better to check the content length, otherwise the client can crash the server by sending a large enough request.
Using *Async methods when reading the content of the request will improve performance.

JIRA - pass credentials for a webrequest to API?

Trying to build a service that will grab info on a JIRA ticket based on an ID passed to it.
I'm calling the API to take the ID passed to the service, tack it onto the URL for the API and get the JSON object.
Problem is, it appears one must be logged on or registered on JIRA in order to use the API.
So if I use the code below to make my request, I get a 404 error, as I do on any browser which I've not used to log onto Jira
public string Get(string id)
{
string html = string.Empty;
string url = #"https://company.atlassian.net/rest/api/latest/issue/" + id;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
return html;
}
I can add credentials to the request like so
request.Credentials = new NetworkCredential("vinnie#company.com","mypassword");
but I've no idea exactly what needs sending. I've tried the email address with which I'm set up in Jira but that doesn't work.
I have a suspicion that Jira adds a cookie to my browser which it uses to validate after the initial config - is that so? If so, what can I add/include on my web request to get it to run?
Am I just wildly off on the right way to access it? Or are there changes that can be made to the Jira side to allow requests?
You have to encode your credentials in Base64 format first and then these credentials can be put into your request as shown below:
string mergedCredentials = string.Format("{0}:{1}", m_Username, m_Password);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
string base64Credentials = Convert.ToBase64String(byteCredentials);
request.Headers.Add("Authorization", "Basic " + base64Credentials);
Hope you're able to solve your problem by this approach!

Unable to connect web exception mvc4

we are doing a facebook posting application using HttpWebRequest.
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
//doing some stuff here.
}
This code is failing at line uisng with unable to connect to server exception.
This is not failing always, but it is failing in 90% cases.
Can somebody advise how best this can be addressed?
Try this (this may not be an answer; just trying to debug your issue), see if it fails like your other one does; then try replacing google.com with your own URL:
WebRequest g = HttpWebRequest.Create("http://www.google.com");
var response = g.GetResponse();

HttpWebResponse displays siteminder login even though URLs are configured to be by passed in Siteminder

I am stumped on this problem and have come humbled to the experts on advice for my problem.
I have an ASP.NET MVC app that is Siteminder enabled. In addition, this app has a section of URLS that are web services which provide data to another application. Those URLS have been configured for "bypass" Siteminder authentication in the Siteminder setup. I've double checked the bypass to make sure the Siteminder configuration is correct. I can enter those URLs in a browser and the JSON data is displayed "without" Siteminder authentication. However....
The problem is when I use HttpWebResponse, Stream and StreamReader to retrieve the JSON data when siteminder is enabled, I get the Siteminder "login page HTML" as the string when StreamReader.ReadToEnd() is evoked instead of the JSON formatted data???
This is baffling because I another developer here can access the same web service and get the "correct" JSON formatted data in a PYTHON app. Also, I put it in a regular ASP.NET app so it's not an MVC issue. I get the same result.
Is there another class or library I should use? Is there a configuration setting I need to pass to the web service call? Any help would be greatly appreciated.
Here is the code of one of the web service calls.
public static string GetData()
{
string host = (string)System.Configuration.ConfigurationManager.AppSettings["WEBSERVICE_GET"];
string URL = host + "Api/GetData";
var end = string.Empty;
try
{
HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (Stream responseStream = response.GetResponseStream())
{
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
{
throw new HttpException((int)response.StatusCode, response.StatusDescription);
}
using (StreamReader reader = new StreamReader(responseStream))
{
end = reader.ReadToEnd();
reader.Close();
}
responseStream.Close();
response.Close();
}
}
catch (Exception ex)
{
EmailNotification.SendErrorEmail("Could not get Data from WEBSERVICE + ex);
}
return end;
}

Internal 500 error in WCf service get response method

Below is my request i get a 500 internal server error at getresponse
string requestData = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Header><h:HeaderItem xmlns:h=\"http://tempuri.org/\">a header item</h:HeaderItem><ActivityId CorrelationId=\"090c553b-bfcc-4e4f-94cd-1b4333fe82a9\" xmlns=\"http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics\">377a454b-b543-4c6f-b4ac-3981029b60e6</ActivityId></s:Header><s:Body><string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">a body item</string></s:Body></s:Envelope>";
byte[] requestDataBytes = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/WebService/");
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8";
request.Headers.Add("SOAPAction", "http://tempuri.org/IWebService/GetMessage");
request.ContentLength = requestDataBytes.Length;
StreamWriter streamWriter = new StreamWriter(request.GetRequestStream());
streamWriter.Write(requestData);
streamWriter.Flush();
streamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
string responseBody = streamReader.ReadToEnd();
I may have an answer for you.
Move the line where you set your headers to the point before you set the content type, and retry your code, as follows:
request.Headers.Add("SOAPAction", "http://tempuri.org/IWebService/GetMessage");
request.ContentType = "text/xml; charset=utf-8";
I make this suggestion based on the documentation for the ContentType property for the WebRequest object from MS:
MS docs on WebRequest
The value for this property is stored in WebHeaderCollection . If
WebHeaderCollection is set, the property value is lost.
Now, I realize we're not expressly setting the WebHeaderCollection, but you are setting a header in that collection, and it made me suspect at least the possibility of this being a problem - rendering your existing ContentType blank, and being interpreted as some default on the inbound side of the web service.
Maybe a long shot, but it might be worth a try.
You should enable WCF trace logging on your server and see if it indicates an error. Typically errors that occur during deserialization or in the WCF layers before hitting your app code will write to this log.
For more info on setting up WCF trace logging, see here or here.