Error while reading body of request message through JSON - rest

I need to read content of message from the request body in WCF REST service like -
SERVICE SIDE CODE
string request = Encoding.UTF8.GetString(OperationContext.Current.RequestContext.RequestMessage.GetBody<byte[]>());
But I am getting an error on the service side, no matter what I try:
Expecting element 'base64Binary' from namespace 'http://schemas.microsoft.com/2003/10/Serialization/'.. Encountered 'Element' with name 'Human', namespace 'http://numans.hr-xml.org/2007-04-15'.
and the service contract is defined as:
//[OperationContract(Name = "LoadMessages", IsOneWay = true)]
[WebInvoke(Method = "POST",
UriTemplate = "/LoadMessages",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
[Description("Inbound Message")]
void LoadMessages();
and the implementation is as:
public void LoadMessages()
{
string content = string.Empty;
//var request = OperationContext.Current.RequestContext.RequestMessage.GetBody<FileState>();
string request = Encoding.UTF8.GetString(OperationContext.Current.RequestContext.RequestMessage.GetBody<byte[]>());
}
CLIENT SIDE CODE
Content that I'm sending is:
string jsonData = "{ \"categoryid\":\"" + file.CategoryId + "\",\"fileId\":\"" + file.FileId + "\" }";
I tried many options to send data from the client like:
var buffer = System.Text.Encoding.UTF8.GetBytes(jsonData);
var content = new ByteArrayContent(buffer);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
and also tried this:
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
Posting request:
HttpResponseMessage executionResult = httpClient.PostAsync($"{url}/LoadMessages", content).Result;
I also tried serializing/de-serializing at client/server end, but that also is not working.
Can someone please suggest code samples what I can try that might work? Or point out what am I doing wrong.
A few more examples of what I tried with the JSON data :
var jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
var details = JObject.Parse(data);
Pasting my client side function for clarity:
HttpClient httpClient = new HttpClient(new HttpClientHandler());
HttpStatusCode statusCode = HttpStatusCode.OK;
string auditMessage = string.Empty;
using (httpClient)
{
var url = ConfigurationManager.AppSettings["APIURL"];
try
{
string jsonData = "{ \"categoryid\":\"" + file.CategoryId + "\",\"fileId\":\"" + file.FileId + "\" }";
//var jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
//var details = JObject.Parse(data);
//var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var buffer = System.Text.Encoding.UTF8.GetBytes(jsonData);
var content = new ByteArrayContent(buffer);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage executionResult = httpClient.PostAsync($"{url}/LoadMessages", content).Result;
statusCode = executionResult.StatusCode;
if (statusCode == HttpStatusCode.Accepted)
{
file.Status = "Success";
}
}
catch (Exception ex)
{
}
}

Here is my demo:
This is the interface document of the service:
This is the request:
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:8012/ServiceModelSamples/service/user");
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-16";
string Json = "{\"Email\":\"123\",\"Name\":\"sdd\",\"Password\":\"sad\"}";
request.ContentLength = Encoding.UTF8.GetByteCount(Json);
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(Json);
myStreamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
//myResponseStream.ResponseSoapContext
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
Console.WriteLine(retString);
Console.ReadKey();
}
}
Feel free to let me know if the problem persists.
UPDATE
Define the Test class:
[DataContract]
public class Test {
[DataMember]
public string categoryid { get; set; }
[DataMember]
public string fileId { get; set; }
}
the implementation is as:
public void LoadMessages(Test test)
{
Test dataObject = OperationContext.Current.RequestContext.RequestMessage.GetBody<Test>(new DataContractJsonSerializer(typeof(Test)));
Console.WriteLine(dataObject.categoryid);
}

Related

Game port to unity: Web posting

I am porting a game from Java Native to Unity. While the game is working correctly, I am having trouble posting the score using the same web services.
Java Code:
public static String gameConfigURL = "http://192.168.0.140/services/scoreupload.svc/json/GetGameConfigurationLite";
public static String scoreUploadURL = "http://192.168.0.140/services/scoreupload.svc/json/Upload";
public static final String MagicKey = "0GmWDa6j";
private static int timeoutConnection = 60000;
public static enum RequestSource
{
Unknown,
System,
Person;
}
public static Response sendRequestForResult(Request request, String Url,
Activity activity, Response response) throws JSONException,
ClientProtocolException, IOException,ConnectTimeoutException {
/** Code to create a JSON request from requestObject **/
JSONObject object = request.getJSON();
JSONObject requestObject = new JSONObject();
requestObject.put("request", object);
Log.v("","REQUEST:"+requestObject.toString());
/** Add code to create a HttpPostRequest **/
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Url);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpResponse httpResponse = null;
String jsonValueString = null;
StringEntity se = null;
try {
se = new StringEntity(requestObject.toString());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "text/json");
/**
* add code to attach the JSON object received from request to the
* HttpPostRequest Add Code to execute HttpRequest
**/
httpResponse = client.execute(httpPost);
/** Get string from the HttpRespnse **/
jsonValueString = EntityUtils.toString(httpResponse.getEntity());
Log.v("","RESPONSE:"+jsonValueString);
/** Create JSON object from incoming String **/
JSONObject repliedObject = new JSONObject(jsonValueString);
response.fromJSON(repliedObject);
return response;
How Do I convert this to unity C#.
So far I have this:
JSONObject j = new JSONObject ();
j.AddField ("Id", "1234567890");
j.AddField ("MagicKey", ApplicationServices.magicKey);
j.AddField ("RequestedBy", "09996f84-1a06-e211-a518-001aa020d699");
j.AddField ("Timestamp", "/Date(1547535370953)/");
j.AddField ("RequestSource", "Person");
j.AddField ("RequestedGameId", "375b43c0-91be-e011-a505-001aa020d699");
j.AddField ("RequestedPersonId", "09996f84-1a06-e211-a518-001aa020d699");
string json = j.ToString ();
Dictionary<string, string> header = new Dictionary<string, string>();
header.Add ("Accept", "application/json");
header.Add ("Content-Type", "text/json");
byte[] encode = Encoding.ASCII.GetBytes (json.ToCharArray ());
WWW getConfig = new WWW (ApplicationServices.gameConfigURL, encode, header);
yield return getConfig;
if (getConfig.error != null) {
Debug.Log (getConfig.error);
} else {
Debug.Log (getConfig.text);
}
This does not seem to work.
For "POST" you should use WWWForm instead of WWW.
Take a look here

IPN Listner not working MVC3

My IPN listner is not working.when i tried with IPN listner Error is showing as follows "We're sorry, we could not send an IPN."
But i can access the IPN Handler url from browser.
here is my IPN handler Code.
public ActionResult IPN()
{
LogMessage ("entering ipn action ");
var formVals = new Dictionary<string, string>();
formVals.Add("cmd", "_notify-validate");
string response = GetPayPalResponse(formVals, true);
LogMessage ("IPN Response received: " + response + " <-- That was response. . . ");
if (response == "VALID")
{
LogMessage("Response Was Verified");
}
else
{
LogMessage("RESPONSE WAS NOT VERIFIED");
}
return Json("Sucess",JsonRequestBehavior.AllowGet);
}
string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox)
{
string paypalUrl = useSandbox
? "https://www.sandbox.paypal.com/cgi-bin/webscr"
: "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(paypalUrl);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
StringBuilder sb = new StringBuilder();
sb.Append(strRequest);
foreach (string key in formVals.Keys)
{
sb.AppendFormat("&{0}={1}", key, formVals[key]);
}
strRequest += sb.ToString();
req.ContentLength = strRequest.Length;
string response = "";
using (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
{
streamOut.Write(strRequest);
streamOut.Close();
using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
{
response = streamIn.ReadToEnd();
}
}
return response;
}
We had faced same issue before I feel it may be because your MVC Application may be published in shared hosting environment Then you have to follow some step to to make MVC RC application works
Here is the blog which help me to solve the issue.Please check this
http://helpnshareidea.blogspot.in/2013/11/mvc3-applications-in-windows-shared.html

Unity3D WWW Post data async

I want to post a JSON to a website using the WWW class, But I get this answer from the server: "Synchronization problem.". Is there a way to change from sync to async? Thank You
You can run your WWW job in a coroutine (WWW supports this well):
using UnityEngine;
public class PostJSON : MonoBehaviour {
void Start () {
string url = "http://your_url_endpoint";
WWWForm form = new WWWForm();
Hashtable headers = form.headers;
headers["Content-Type"] = "application/json";
Hashtable data = new Hashtable();
data["message"] = "a sample message sent to service as json";
string json = JSON.JsonEncode(data);
byte[] bytes = Encoding.UTF8.GetBytes(json);
WWW www = new WWW(url, bytes, headers);
StartCoroutine(WaitForRequest(www));
}
IEnumerator WaitForRequest(WWW www)
{
yield return www
// check for errors
if (www.error == null)
{
Debug.Log("WWW Ok!: " + www.data);
} else {
Debug.Log("WWW Error: "+ www.error);
}
}
}
Here you have a running project which I use to talk to a json based REST service called KiiCloud:
http://blog.kii.com/?p=2939
HTH
The answer from German was very helpful, but I made some tweaks so that it'll compile and run (with sample serialization / deserialization bits).
Just pass in the BaseUrl you want to post to, i.e.
http://www.domain.com/somecontroller/someaction or whatever.
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Person
{
public string Name;
}
[Serializable]
public class Response
{
public string SomeValue;
}
public class PostJSON : MonoBehaviour
{
public string BaseUrl;
private WWWForm form;
private Dictionary<string, string> headers = null;
void Start ()
{
var basUrlNotSpecified = string.IsNullOrEmpty(BaseUrl);
if(basUrlNotSpecified)
{
Debug.LogWarning("BaseUrl value not specified. Post abandoned.");
return;
}
form = new WWWForm();
headers = form.headers;
headers["Content-Type"] = "application/json";
headers["Accept"] = "application/json";
var person = new Person
{
Name = "Iulian Palade"
};
var json = JsonUtility.ToJson(person);
byte[] bytes = Encoding.UTF8.GetBytes(json);
WWW www = new WWW(BaseUrl, bytes, headers);
StartCoroutine(WaitForRequest(www));
}
IEnumerator WaitForRequest(WWW www)
{
yield return www;
if (www.error == null)
{
Debug.Log("WWW Ok!: " + www.text);
var response = JsonUtility.FromJson<Response>(www.text);
Debug.Log(response.SomeValue);
}
else
{
Debug.Log("WWW Error: "+ www.error);
}
}
}

ASP.NET MVC Web API 4 REST Webservice: PUT/POST - ing a List of objects

Wondering if its possible and/or supported to put/post an entire object to REST Webservice, as opposed to just some name/value pairs ?
If so, can a List of objects be put/post-ed as well ?
I figured it may be possible, since a GET request is able to return a List of objects, I'd like to do the "reverse" operation with the updated objects (and not send them one at a time, or worse, in individual pieces via name/value pairs) ?
I understand this is a very basic question, but the approach I've taken so far was to just try and code the PUT and get it working (which works if the PUT function has no arguments, like:
public class AObjectController : ApiController
{
public List<int[]> Put()
{
List<int[]> ret = new List<int[]>();
ret.Add(new int[] {-1, 1111});
ret.Add(new int[] {-2, 2222});
return ret;
}
If I specify a single object, or list of objects, I get exceptions:
public List<int[]> Put(AObject object) **CASE 1**
public List<int[]> Put(List<AObject> objects) **CASE 2**
{
List<int[]> ret = new List<int[]>();
ret.Add(new int[] { -1, 1111 });
ret.Add(new int[] { -2, 2222 });
return ret;
}
CASE 1: public List(int[]) Put(AObject object)
CASE 2: public List(int[]) Put(List(AObject) objects)
Heres the code on the client side that is making the call:
public int writeAll(List<T> data)
{
_sendBuffer =
JsonConvert.SerializeObject(
tabletData,
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }
);
byte[] b = StringHelper.GetBytes(_sendBuffer);
string url = ContructUrlRequest(null, null);
WebRequest request = WebRequest.Create(url);
request.Method = "PUT";
request.ContentType = "application/json";
request.ContentLength = b.Length;
request.Credentials = CredentialCache.DefaultCredentials;
((HttpWebRequest)request).UserAgent = "...";
//((HttpWebRequest)request).AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(b, 0, b.Length);
requestStream.Flush();
requestStream.Close();
}
WebResponse response = request.GetResponse();
if (response == null)
{
return -1;
}
StreamReader sr = new StreamReader(response.GetResponseStream()); ;
_recieveBuffer = sr.ReadToEnd();
List<int[]> _resultData = JsonConvert.DeserializeObject<List<int[]>>(
_recieveBuffer,
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }
);
return data.Count;
}
Thank you.
Used the serialization write code from server on my client side and it worked
public int writeAll(List<AObject> aObjects)
{
string url = ContructUrlRequest(null, null);
WebRequest request = WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Put;
request.ContentType = "application/json; charset=utf-8";
request.Credentials = CredentialCache.DefaultCredentials;
((HttpWebRequest)request).UserAgent = "going insane";
JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.TypeNameHandling = TypeNameHandling.Objects | TypeNameHandling.Arrays;
serializerSettings.Converters.Add(new IsoDateTimeConverter());
JsonSerializer serializer = JsonSerializer.Create(serializerSettings);
using (Stream requestStream = request.GetRequestStream())
{
using (StreamWriter streamWriter = new StreamWriter(requestStream, new UTF8Encoding(false, true)))
{
using (JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter))
{
serializer.Serialize(jsonTextWriter, aObjects);
}
}
}
WebResponse response = request.GetResponse();
if (response == null)
{
Log.Info(FIDB.TAG_WSBUFFER, "WSBuffer.writeAll: response = NULL");
return -1;
}
StreamReader sr = new StreamReader(response.GetResponseStream());
_recieveBuffer = sr.ReadToEnd();
_resultData = JsonConvert.DeserializeObject<List<int[]>>(
_recieveBuffer,
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }
);
return tabletData.Count;
}

ASP.NET JSON Web Service Response format

I have written one simple web service which get product list in JSONText which is string object
Web Service code is below
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
/// <summary>
/// Summary description for JsonWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class JsonWebService : System.Web.Services.WebService
{
public JsonWebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetProductsJson(string prefix)
{
List<Product> products = new List<Product>();
if (prefix.Trim().Equals(string.Empty, StringComparison.OrdinalIgnoreCase))
{
products = ProductFacade.GetAllProducts();
}
else
{
products = ProductFacade.GetProducts(prefix);
}
//yourobject is your actula object (may be collection) you want to serialize to json
DataContractJsonSerializer serializer = new DataContractJsonSerializer(products.GetType());
//create a memory stream
MemoryStream ms = new MemoryStream();
//serialize the object to memory stream
serializer.WriteObject(ms, products);
//convert the serizlized object to string
string jsonString = Encoding.Default.GetString(ms.ToArray());
//close the memory stream
ms.Close();
return jsonString;
}
}
now it give me resoponse like below :
{"d":"[{\"ProductID\":1,\"ProductName\":\"Product 1\"},{\"ProductID\":2,\"ProductName\":\"Product 2\"},{\"ProductID\":3,\"ProductName\":\"Product 3\"},{\"ProductID\":4,\"ProductName\":\"Product 4\"},{\"ProductID\":5,\"ProductName\":\"Product 5\"},{\"ProductID\":6,\"ProductName\":\"Product 6\"},{\"ProductID\":7,\"ProductName\":\"Product 7\"},{\"ProductID\":8,\"ProductName\":\"Product 8\"},{\"ProductID\":9,\"ProductName\":\"Product 9\"},{\"ProductID\":10,\"ProductName\":\"Product 10\"}]"}
But i am looking for below out put
[{"ProductID":1,"ProductName":"Product 1"},{"ProductID":2,"ProductName":"Product 2"},{"ProductID":3,"ProductName":"Product 3"},{"ProductID":4,"ProductName":"Product 4"},{"ProductID":5,"ProductName":"Product 5"},{"ProductID":6,"ProductName":"Product 6"},{"ProductID":7,"ProductName":"Product 7"},{"ProductID":8,"ProductName":"Product 8"},{"ProductID":9,"ProductName":"Product 9"},{"ProductID":10,"ProductName":"Product 10"}]
can any one tell me what is actual problem
Thanks
First there was a change with ASP.NET 3.5 for security reasons Microsoft added the "d" to the response. Below is a link from Dave Ward at the Encosia that talks about what your seeing:
A breaking change between versions of ASP.NET AJAX. He has several posts that talks about this that can help you further with processing JSON and ASP.NET
Actually, if you just remove the
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
from the method, and you return the jsonString that you serialized using the JavaScriptSerializer you will get exactelly the output that you were looking for.
Notice that u have double quotes beside ur array in your response.In this way u return json format not json object from ur web method.Json format is a string.Therefore u have to use json.parse() function in order to parse json string to json object.If u dont want to use parse fuction,u have to remove serialize in ur web method.Thus u get a json object.
in .net web service
[WebMethod]
public string Android_DDD(string KullaniciKey, string Durum, string PersonelKey)
{
return EU.EncodeToBase64("{\"Status\":\"OK\",\"R\":[{\"ImzaTipi\":\"Paraf\", \"Personel\":\"Ali Veli üğişçöıÜĞİŞÇÖI\", \"ImzaDurumTipi\":\"Tamam\", \"TamamTar\":\"1.1.2003 11:21\"},{\"ImzaTipi\":\"İmza\", \"Personel\":\"Ali Ak\", \"ImzaDurumTipi\":\"Tamam\", \"TamamTar\":\"2.2.2003 11:21\"}]}");
}
static public string EncodeToBase64(string toEncode)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(toEncode);
string returnValue = System.Convert.ToBase64String(bytes);
return returnValue;
}
in android
private static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}
private void LoadJsonDataFromASPNET()
{
try
{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(this.WSURL + "/WS.asmx/Android_DDD");
JSONObject jsonObjSend = new JSONObject();
jsonObjSend.put("KullaniciKey", "value_1");
jsonObjSend.put("Durum", "value_2");
jsonObjSend.put("PersonelKey", "value_3");
StringEntity se = new StringEntity(jsonObjSend.toString());
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
// httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
HttpEntity entity = response.getEntity();
if (entity != null)
{
InputStream instream = entity.getContent();
String resultString = convertStreamToString(instream);
instream.close();
resultString = resultString.substring(6, resultString.length()-3);
resultString = new String(android.util.Base64.decode(resultString, 0), "UTF-8");
JSONObject object = new JSONObject(resultString);
String oDurum = object.getString("Status");
if (oDurum.equals("OK"))
{
JSONArray jsonArray = new JSONArray(object.getString("R"));
if (jsonArray.length() > 0)
{
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String ImzaTipi = jsonObject.getString("ImzaTipi");
String Personel = jsonObject.getString("Personel");
String ImzaDurumTipi = jsonObject.getString("ImzaDurumTipi");
String TamamTar = jsonObject.getString("TamamTar");
Toast.makeText(getApplicationContext(), "ImzaTipi:" + ImzaTipi + " Personel:" + Personel + " ImzaDurumTipi:" + ImzaDurumTipi + " TamamTar:" + TamamTar, Toast.LENGTH_LONG).show();
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}