WCF GET returning XML instead of JSON on server - json

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.

Related

HTTP-GET via SSIS

I have some ethernet device which collect data and it's possible to download it via data export interface: HTTP-GET query returns the data in [Content-Type: text/plain Charset: utf-8]
I saw this: How to make an HTTP request from SSIS? - it rather doesn't work for me (C# is a little Chinese for me) and it's about how to fetch this data to variable into SSIS
In your SSIS package add a C# Script Task
Edit the Script Task
At the top with the other using statements add using System.Net;
in Main use the following code snippet to make a GET request (Note: Change "https://somewhere.com/contacts/get" to your actual endpoint.)
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://somewhere.com/contacts/get");
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}

WCF CustomBehavior set JSON/stream for context

Similar to this question, I need to send back JSON.
WCF ResponseFormat For WebGet
But I'm working from within a WCF Behavior being called by a BizTalk 2010 SendPort Adapter.
I'm inside this method:
public object BeforeSendRequest(ref Message request, IClientChannel channel)
So I have the Message and the channel that I can manipulate.
I think the direction is something like this:
1) //WebOperationContext.Current.OutgoingResponse.ContentType = “text/plain”;
or
2) OperationContext.Current.... something - but I don't know the object model well.
I'm currently using the MemoryStream:
byte[] byteArrayJSON = Encoding.UTF8.GetBytes(strJSON);
MemoryStream memStreamJSON = new MemoryStream(byteArrayJSON);
//WebOperationContext.Current.OutgoingResponse.ContentType = “text/plain”;
Message newMessage = Message.CreateMessage(MessageVersion.None, "", memStreamJSON);
...
request = newMessage; // substitute my new message for the original one.
My headers have this:
Content-Type: application/json
Accept: application/json
I think these are the lines I need, but still testing...
WebBodyFormatMessageProperty bodyFormat = new WebBodyFormatMessageProperty(WebContentFormat.Json);
newMessage.Properties.Add(WebBodyFormatMessageProperty.Name, bodyFormat);
It looks like maybe now I should pass XML and this will cause the serialization to happen? I'm now on to my next error:
System.ArgumentException: Encountered unexpected namespace 'http://schemas.datacontract.org/2004/07/System.IO'. The namespace must be empty.
Parameter name: ns
Going to try "raw":
WebBodyFormatMessageProperty bodyFormat = new WebBodyFormatMessageProperty(WebContentFormat.Json);
newMessage.Properties.Add(WebBodyFormatMessageProperty.Name, bodyFormat);

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:

Sending a json serialized object containing a escaped string using HttpWebRequest on mono

The requirement serialize a class and send it to the server.
Dev environment:
MonoDevelop 3.0.6
Runtime:
Mono 2.10.9 (tarball)
GTK 2.24.10
GTK# (2.12.0.0)
Operating System:
Mac OS X 10.7.4
The class contains a string with an escaped double quote in it.
class CustomClass
{
public string foo = "hi!\"";
}
The issue is that when I serialize it, encode it and create a URI object, the backslash used to escape double quote in the variable foo is converted into a forward slash, thus breaking the json.
Below are values of the different variables of the URI instance
Uri:
http://myserver/hello_world/0/{"foo":"hi!/""}
AbsoluteUri:
http://myserver/hello_world/0/%7B%22foo%22%3A%22hi%21/%22%22%7D
OriginalString:
http://myserver/hello_world/0/%7B%22foo%22%3A%22hi%21%5C%22%22%7D
The HttpWebRequest send the value "http://myserver/hello_world/0/{"foo":"hi!/""}" to the server, but for my requirement it should use the OriginalString to get a valid response from the server.
If i test the code on .NET the OriginalString is being sent to the server by the HttpWebRequest class, but there is additional code (hack) which doesn't work on mono mac
string paq = requestUri.PathAndQuery;
FieldInfo flagsFieldInfo = typeof(Uri).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
ulong flags = (ulong)flagsFieldInfo.GetValue(requestUri);
flags &= ~((ulong)0x30); // Flags.PathNotCanonical|Flags.QueryNotCanonical
flagsFieldInfo.SetValue(requestUri, flags);
The code :
object messageObject = new CustomClass();
//try 1
//string jsonString = Uri.EscapeUriString(JsonConvert.SerializeObject(message2));
//try 2
//string jsonString = Uri.EscapeDataString(JsonConvert.SerializeObject(message2));
//try 3
string jsonString = System.Web.HttpUtility.UrlEncode(JsonConvert.SerializeObject(messageObject));
Uri uri = new Uri(string.Format("http://myserver/hello_world/0/{0}", jsonString));
//try 4:
//HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri.AbsoluteUri);
//try 5
//HttpWebRequest request =(HttpWebRequest)WebRequest.Create(string.Format("http://myserver/hello_world/0/{0}",jsonString));
//try 6
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri.OriginalString);
try
{
using (HttpWebResponse resp = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(resp.GetResponseStream());
string jsonResponse = reader.ReadToEnd();
}
}
catch (WebException wex)
{
Debug.WriteLine(wex.ToString());
}
As you can see I have tried using Uri.EscapeUriString, Uri.EscapeDataString and System.Web.HttpUtility.UrlEncode and using the AbsouluteUri and OriginalString to create the WebRequest instance and also creating it using a string.
I have also tried using the following code in the config.
<uri>
<schemeSettings>
<clear/>
<add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes"/>
</schemeSettings>
</uri>
But none of the methods work and the encoding is lost when the request in created.
Any ideas to get this to work will be appreciated.
Update:
I have tried a lot of things including testing with some 3rd party open source code, but still faced the same issue when sending in an encoded url.
I modified the code to use WebClient instead of WebRequest but still no luck.
So the solution that worked for me on both MonoMac an MonoTouch(simulator, i haven't tested it on the device) was to create the request using TcpClient.
using (TcpClient tc = new TcpClient()) {
tc.Connect ("myserver", 80);
using (NetworkStream ns = tc.GetStream()) {
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(ns)) {
using (System.IO.StreamReader sr = new System.IO.StreamReader(ns)) {
sw.Write("GET /hello_world/0/%7B%22foo%22:%22hi!%5C%22%22%7D HTTP/1.1 Host:myserver \r\n\r\n");
sw.Flush ();
string line;
while ((line=sr.ReadLine())!=null)
Console.Write (line);
}
}
}
}
I have tried a lot of things including testing with some 3rd party open source code, but still faced the same issue when sending in an encoded url.
I modified the code to use WebClient instead of WebRequest but still no luck.
So the solution that worked for me on both MonoMac an MonoTouch(simulator, i haven't tested it on the device) was to create the request using TcpClient.
using (TcpClient tc = new TcpClient()) {
tc.Connect ("myserver", 80);
using (NetworkStream ns = tc.GetStream()) {
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(ns)) {
using (System.IO.StreamReader sr = new System.IO.StreamReader(ns)) {
sw.Write("GET /hello_world/0/%7B%22foo%22:%22hi!%5C%22%22%7D HTTP/1.1 Host:myserver \r\n\r\n");
sw.Flush ();
string line;
while ((line=sr.ReadLine())!=null)
Console.Write (line);
}
}
}
}

Consuming a post method in WCF REST template 40 - 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.