Consuming a post method in WCF REST template 40 - JSON - json

am getting rather frustrated at the lack of information out there on how to post data to a WCF REST method in JSON form. I have tried almost everything out there. Google is just returning purple links at this point...
What I am looking for is a way to send a JSON object to my method so it can shelve all of the data for me. What I am currently trying to get working is below:
The Method header:
[WebInvoke(Method = "POST", UriTemplate = "role/new", ResponseFormat = WebMessageFormat.Json)]
void AddNewRole(Stream streamdata)
The logic from the client app:
string json = JsonConvert.SerializeObject(role);
byte[] buffer = Encoding.UTF8.GetBytes(json);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://IP/InfoService/role/new");
request.Method = "POST";
request.Credentials = new NetworkCredential("", "");
request.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
{
sw.Write(json);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
MessageBox.Show(sr.ReadToEnd());
}
Using this method I get an accepted response from the service, but it is a blank response and no new data gets added to the database. Granted, it is possible that there is a problem with my database update methods. Either way, can anyone help me figure out where I am going wrong?
EDIT: I now have fiddler able to test on the test client, and as expected there are problems with my DB queries. Ill post back soon.
EDIT2: Finally worked out the database problems, I have now successfully invoked through fiddler.
EDIT3: Its working now, thanks to nobody.

The code above has been edited, it works.

Related

.Net Core send/receive JSON over TCP

I want to send and receive JSON over TCP.
QUESTION: I have to send and receive JSON in my TCP client-server. How can I achieve it?
I use TcpListener and TcpClient to connect and I have this code:
NetworkStream stream = client.GetStream();
var serializer = new JsonSerializer();
var sr = new StreamReader(stream, new UTF8Encoding(), false);
var jsonTextReader = new JsonTextReader(sr);
var data = serializer.Deserialize(jsonTextReader).ToString();
Console.WriteLine("Received: {0}", data);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter writer = new JsonTextWriter(sw);
writer.WriteValue('1');
byte[] buffer = Encoding.ASCII.GetBytes(writer.ToString());
stream.Write(buffer, 0, buffer.Length);
Can I do it better? The client has to receive JSON(I use Newtonsoft.Json) and I don't know if it is even good code. Maybe you write me some good practices? Or maybe some tips.
EDIT.
Now I wrote something like this:
public static T DeserializeFromStream<T>(Stream stream)
{
using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
return new JsonSerializer().Deserialize<T>(jsonTextReader);
}
}
And it doesn't work because Java client send me array like: [{"name" : "logo", "session" : "i3fnj34njn780"}] So how can I fix this problem? I want call it this way: Method ar = DeserializeFromStream<Method>(client.GetStream()); Trim and Replace doesn't work for me here.
byte[] buffer = Encoding.ASCII.GetBytes(writer.ToString());
This is incorrect. Per RFC4627:
Encoding
JSON text SHALL be encoded in Unicode. The default encoding is
UTF-8.
You are not sending JSON.
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter writer = new JsonTextWriter(sw);
This is unnecessarily writing a SB. Write directly into the network stream:
using (NetworkStream stream = client.GetStream()) {
using (TextWriter tw = new StreamWriter(stream, Encoding.UTF8)) {
using (JsonWriter writer = new JsonTextWriter(tw)) {
...
}
}
}
Also, use using.
Plus, everything #CodeCaster says. This should be a proper Web API, not some rogue TCP server. Not only the obvious issue of having more than one request type (ie. routing), but you have to consider proxies (none will allow some arbitrary port), server authentication (you must tunnel through HTTPS and validate the server cert in the Android APP), make allowance for web caching, HTTP headers etc etc. And you need proper error states and error codes for your 'protocol', which HTTP provides out-of-the-box. And a good job would be to model a proper REST API, and likely a good data model on top of JSON, like JSON-API.

Json put/get/post in Restful webservices not working

I am trying to pass parameters to a server and extract the report in csv format. So the code i have has PUT/GET/POST in the order. I could get GET and POST work, but when i add PUT there is no error just blank screen.
String output1 = null;
URL url = new URL("http://<servername>/biprws/raylight/v1/documents/12345/parameters");
HttpURLConnection conn1 = (HttpURLConnection) url.openConnection();
conn1.setRequestMethod("PUT");
conn1.setRequestProperty("Accept", "application/json");
conn1.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn1.setDoInput(true);
conn1.setDoOutput(true);
String body = "<parameters><parameter><id>0</id><answer><values><value>EN</value></values></answer></parameter></parameters>";
int len1 = body.length();
conn1.setRequestProperty("Content-Length", Integer.toString(len1));
conn1.connect();
OutputStreamWriter out1 = new OutputStreamWriter(conn1.getOutputStream());
out1.write(body, 0, len1);
out1.flush();
What i am trying to do is pass parameter EN to the report and refresh it, take the output in csv using GET. POST is used for login to the server. I could make GET and POST work and get the output in CSV but not refreshed one.
Appreciate very much any help here.
Thanks,
Ak
What is the response code from the server when using PUT?
A PUT may not actually return a body to display on the screen; often times a PUT will only return a 200 or 204 response code. 204 would clearly mean that the server took the data and applied it, but is not sending you anything back, 200/201 may include a response, but maybe not. It depends on the folks who implemented the API.
https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html (section 9.6)
Should a RESTful 'PUT' operation return something

WCF GET returning XML instead of JSON on server

I have a WCF service with a webHttpBinding defined. The interface has a single method:
[OperationContract(Action = "*")]
[WebGet(UriTemplate = "/",RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
Stream GetServerInfo();
Which returns a stream with encoded JSON:
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
ServerData r = ServerData.Instance;
r.upTime = (DateTime.Now - r._startupTime).ToString(#"dd\.hh\:mm\:ss");
using (Process proc = Process.GetCurrentProcess())
{
r.usedMemory = ((double)proc.PrivateMemorySize64) / 1024 / 1024;
}
r.activeSessions = getServiceData().Count();
string jsCode = "displayData" + "("+
new JavaScriptSerializer().Serialize(r)
+")";
WebOperationContext.Current.OutgoingResponse.ContentType = "application/javascript";
Console.WriteLine(jsCode);
return new MemoryStream(Encoding.UTF8.GetBytes(jsCode));
When used on my devel PC it works fine. I get sth like:
displayData({"_startupTime":"\/Date(1435867525056)\/","serverVersion":"1.0.0.8","startUpTime":"2. 7. 2015 22:05:25","acceptedConnections":0,"upTime":"00.00:00:00","usedMemory":21.265625,"activeSessions":0})
However, after deploy to a remote server I get only following response and I want to get a JSON:
<GetServerInfoResponse xmlns="http://tempuri.org/"><GetServerInfoResult>ZGlzcGxheURhdGEoeyJfc3RhcnR1cFRpbWUiOiJcL0RhdGUoMTQzNTg2ODUwMjc5NClcLyIsInNlcnZlclZlcnNpb24iOiIxLjAuMC44Iiwic3RhcnRVcFRpbWUiOiI3LzIvMjAxNSAxOjIxOjQyIFBNIiwiYWNjZXB0ZWRDb25uZWN0aW9ucyI6MCwidXBUaW1lIjoiMDAuMDA6MDA6MDAiLCJ1c2VkTWVtb3J5IjoyNy40NzY1NjI1LCJhY3RpdmVTZXNzaW9ucyI6MH0p</GetServerInfoResult></GetServerInfoResponse>
Note I call for the request locally directly on the server. But on remote call over network the response is the same. If I put a log output of the string to console I can see the output string is correct.
The config files are identical (except for addresses).
--edit
With the try-fail method I found out the string inside the XML response is the JSON string encoded in Base64.
Can somebody please help me whats wrong?
After some research I did not find any solution. However, after restarting OS (Win Server 2012) and rebuilding it just works like a charm.

Json: the remote server returned an error (500) internal server error

i am trying to read a web service in Json format
here is my code:
WebClient wc = new WebClient();
wc.UseDefaultCredentials = true;
var data = wc.DownloadString(JsonUri);
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(data));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<PaymentMethod>));
var result = serializer.ReadObject(ms);
ms.Close();
ms.Dispose();
i get an error on this line:
var data = wc.DownloadString(JsonUri);
the JsonUri is : http://avaris.kwekud.com/api/v1/items/uniqueitem/?username=joel&api_key=959dd41efd06b84ca7f10b1b12f5f3e6567c07dc&format=json
Any Help
thanks
It looks like there is a problem in the python code on the server that is returning the API. A good idea is to try to make the call from outside of your code to make sure that it is not your code. Any packet sniffing tool eg firebug in firefox will be able to tell you if the call is going wrong pr its your code being badly formed.
It looks like the API is currently broken, so you should put a try ... catch in there and handle the exception for situations like this:

WCF JSON returned as null

Following this tutorial: I have created a WP8 Mobile Application and trying to call my WCF web service. When calling the WCF service in the browser, I can see the JSON returned with no problems at all. However, when I call the WCF service in my mobile application, I don't get anything back. I have no clue where I am going wrong.
This is the code that call the WCF:
string ServiceUri = "urlgoeshere";
WebClient proxy = new WebClient();
proxy.DownloadStringCompleted += new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri(ServiceUri));
And the event handler:
Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<SightingType>));
var result = obj.ReadObject(stream) as List<SightingType>;
What am I doing wrong? I've obviously changed the ServiceUri to "urlgoeshere" but rest assured, the actual URL works perfectly, 100% A-OK when I run it in my browser. When running it in this mobile app however, it doesn't work. Can anyone see the obvious problem?
Update
If I do:
var result = obj.ReadObject(stream);, and if I step into stream, I can see a:
ReadTimeout = 'stream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'