JSON post from c# fails with 500 error - c#

I have a c# winforms app in which I'm trying to call into a web service for which I control the code (on both ends). I know the web service is fine because I can call it from jquery with no problems and valid json is returned. But when I call it from c#, I get this error: "The remote server returned an error: (500) Internal Server Error." In the debugger I cannot glean any more details than that.
Here is my c# caller code:
private string GetMemberCheckInData() {
string response = string.Empty;
string fullURL = RootServiceURL + "MemberCheckIn";
var httpWebRequest = (HttpWebRequest) WebRequest.Create(fullURL);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
string json = "{\"scanCode\":\"" + APIKey + "\"," +
"\"siteID\":\"2\"," +
"\"revenueGroupID\":\"0\"," +
"\"employeeID\":\"12345\"}";;
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
using(var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
response = streamReader.ReadToEnd();
}
}
return response;
}
Here is the literal JSON that is being sent:
{"scanCode":"***8G9V3MA39H0N****","siteID":"2","revenueGroupID":"0","employeeID":"12345"}
Here is the c# web service code (works fine when called from jquery):
[WebMethod]
public void MemberCheckIn(string scanCode, int siteID, int revenueGroupID, int employeeID)
{
...code is never reached...
}
The web service function is never actually entered; I confirmed this with the debugger. When I call it from jquery, I can debug right into it. So it seems the request is being rejected by the .net runtime or IIS or something.
Any ideas what I am doing wrong?

Your webmethod is expecting you to pass parameters in to it.
string fullURL = RootServiceUrl + "MemberCheckIn?scanCode=X&siteID=1...etc.

Related

JIRA web request causes issues

I am trying to to extract data from Jira via JIRA REST API from a c# application. to do so I execute this method :
public string RunQuery(JiraRessource resource, string project_id, int startAt, int maxResults, string method = "GET")
{
string url = string.Format(m_BaseUrl);
if (project_id != null)
{
string jql = "search?jql=project=" + project_id;
url = string.Format("{0}{1}", url, jql);
}
string jqr = "&startAt=" + startAt + "&maxResults=" + maxResults;
url = string.Format("{0}{1}", url, jqr);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = method;
string base64Credentials = GetEncodedCredentials();
request.Headers.Add("Authorization", "Basic " + base64Credentials);
string result = string.Empty;
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
return result;
}
}
}
I execute this method in a loop in order to be able to get all issues after I read that the REST API only gives 50 issues each time. I get errors such as "connection timed out" or "unable to read data from the transport connection". I searched online and all i found is that the connection to the server is lost but I do not know how to solve this.
If anyone knows anything about the reason why I'm getting this error or how to solve it, I will be very thankful.
A few things to try below. If any of these work, it will help you get to the source of the problem.
Try with a request for a small amount of data:
string url = "<your base url>/search?jql=startAt=1&maxResults=1&fields=created";
Try that same url in a web browser (log in to Jira first with the same creds you are using in your C# code)
Try with this code before the call:
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (Object obj, X509Certificate X509certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors)
{
return true;
};
Check the permissions in Jira for the user id you are using for the api call.

Console application, first webrequest doesn't get response, later does, why?

I am developing console application for API integration. This follow fetching token in first request and then getting report in second request after passing token.
string token = GetToken(app_id); // API call, which is working fine and getting token
string reportquerystring = "path?token=" + token;
WebRequest req = WebRequest.Create(#reportquerystring);
req.Method = "GET";
req.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
var resp = req.GetResponse() as HttpWebResponse;
using (Stream downloadstream = resp.GetResponseStream())
{
XmlDocument reportxml = new XmlDocument();
string filename = "location\\";
string reportxmlString = (new StreamReader(downloadstream)).ReadToEnd();
reportxml.LoadXml(reportxmlString);
string json = JsonConvert.SerializeXmlNode(reportxml);
System.IO.File.WriteAllText(filename + "data_" + app_id + ".txt", json);
}
Here when I run this code while debugging, on the first call of download report, response xml is empty, when I drag debugger again before call, in the same run, then it gets response properly. But until and unless I figure out the reason why first call to download report API is not working or how I can make it work, I can not proceed.
Any suggestions ?

Get Request in C# Returning 401 Not Authorised

Currently trying to do a Get request as part of a c# program. The request works fine on Postman as it uses a header for authorization. However I cannot get the code working for the program to use this header correctly in its Get request. I've had a good look around and tried various bits of code I've found but haven't managed to resolve it so any help would be appreciated!
public string Connect()
{
using (WebClient wc = new WebClient())
{
string URI = "myURL.com";
wc.Headers.Add("Content-Type", "text");
wc.Headers[HttpRequestHeader.Authorization] = "Bearer OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3";//this is the entry code/key
string HtmlResult = wc.DownloadString(URI);
return HtmlResult;
}
}
Above is one method inside the class.
Below is another attempt which is an extension method that gets passed the URL:
public static string GetXml(this string destinationUrl)
{
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(destinationUrl);
request.Method = "GET";
request.Headers[HttpRequestHeader.Authorization] = "Bearer
OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3";
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new
StreamReader(responseStream).ReadToEnd();
return responseStr;
}
else
{
Console.Write(String.Format("{0}({1})",
response.StatusDescription, response.StatusCode));
}
return null;
}
Might I recommend the very handy RestSharp package (find it on Nuget).
It turns your current code into something like
public string Connect()
{
var client = new RestClient();
var request = new RestRequest("myURL.com", Method.GET);
request.AddParameter("Authorization", "Bearer OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3");
var response = client.Execute(request);
return response.Content;
}
It's much more succinct and easier to use (in my opinion) and thus lessens the likelihood of passing in or using incorrect methods.
If you're still having issues getting data back/connecting. Then using PostMan click Code in the upper right of PostMan and select the C# (RestSharp) option. Whatever is generated there matches exactly what PostMan is sending. Copy that over and you should get data back that matches your PostMan request.

Send data form C# to Visual Basic API

I have a API in C# and another one in Visual Basic. I need to send some information in JSON format from the API in C# to the API in Visual Basic, hopefully using POST verb. The context of the situation is like this. A mobile application send information to the API in C#, the API save the data in a database located in the server, then if the information is correct the API in C# have to send the data to the Visual Basic API and save it in other server. Anybody knows hoy to send the data from C# to Visual Basic? Thanks.
It doesn't matter that one API is in C# and the other in VB. As long as the json you are sending is valid (try validating the json you send at jsonlint.com) and can be mapped to an object the API accepts everything should be fine.
It seems like the endpoint api is not accepting the request.
This is my C# code
try
{
var request = (HttpWebRequest)WebRequest.Create(URL);
request.ContentType = "application/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
var1 = "example1",
var2 = "example2"
});
streamWriter.Write(json);
}
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return Request.CreateResponse(HttpStatusCode.OK, new { Respuesta = result }, "application/json");
}
}
catch(Exception e)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, new { Respuesta = e.ToString() }, "application/json");
}
}
And this is my function in Visual Basic
Public Function PostValue(ByVal json as String)
return json
End Function
Thats all. And throw me this error
{
"Respuesta": "System.Net.WebException: The remote server returned an error: (404) Not Found.\r\n at System.Net.HttpWebRequest.GetResponse()\r\n at Servicios.Controllers.SAPEnviarFacturasController.SAPEnviarFacturas() in C:\TFS\Servicios\Controllers\SAPEnviarFacturasController.cs:line 44"
}

Posting Credentials To C# Login Page

I wrote a test login page(.aspx) which has one Postback method and a second static Webmethod call. The javascript function takes the value from "txt1" and "txt2" and calls the C# [WebMethod]
HTML:
<input type="text" id="txt1" />
<input type="text" id="txt2" />
//JS function sends values to C# WebMethod
PageMethods.ReceiveUsernamePassword(txt1.value, txt2.value);
C#:
[WebMethod]
public static string ReceiveUsernamePassword(string user, string pass)
{
File.AppendAllText(#"C:\Z\upjs.txt", user + " " + pass + " js " + "\r\n\r\n\r\n");
return "Success JS";
}
A separate Client app that simulates a POST using following code below. URL points to localhost:1073/PostData_Server/Default.aspx/ReceiveUsernamePassword:
using (WebClient client = new WebClient())
{
System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
reqparm.Add("user", "user1");
reqparm.Add("pass", "password1");
byte[] responsebytes = client.UploadValues("http://local:1073/PostData_Server/Default.aspx", "POST", reqparm);
string responsebody = Encoding.UTF8.GetString(responsebytes);
}
Instead of getting "Success" or "Success JS" on my test client app, I am receiving the entire HTML document as the response message. Also no text file is written on the server side. I verified that it was not an error in my client app by downloaing Poster(https://addons.mozilla.org/en-us/firefox/addon/poster/). It too receive the entire HTML document as the response. How can I correct this?
Just thought I'd update my findings on this question. It turns out in order to call the [WebMethod], the ContentType must be set to "application/json". You also cannot use WebClient.UploadValues() because it wont let you change the ContentType. So in order to send the correct POST signature, you must use the HttpWebRequest Class.
Also note: username and password sent MUST be in json format!
HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
myHttpWebRequest.Method = "POST";
myHttpWebRequest.ContentType = "application/json; encoding=utf-8";
using (var streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream()))
{
string json = "{user:\"user1\",pass:\"pass1\"}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
responsebody = streamReader.ReadToEnd();
}

Categories