Deserializing the object inside an http post - c#

Hi I am trying to deserialize an Object from a HttpPost method call inside an authorize attribute.I am using ASP.NET Web Api Framework.
Here is my code:
public override void OnAuthorization(HttpActionContext actionContext)
{
var rezult = DeserializeStream<EvaluationFormDataContract>(actionContext.Request.Content.ReadAsStreamAsync().Result);
}
private T DeserializeStream<T>(Stream stream)
{
var binaryFormatter = new BinaryFormatter();
var rez = binaryFormatter.Deserialize(stream);
var t = (T)binaryFormatter.Deserialize(stream);
return t;
}
When this code gets executed I get this exception when the binaryFormatter tryes to deserialize it:
The input stream is not a valid binary format. The starting contents (in bytes) are: 73-74-75-64-65-6E-74-41-73-73-69-67-6E-6D-65-6E-74 ...
What am I doing wrong?

You are trying to use BinaryFormatter to binary deserialize data which was not binary serialized. From data you sent I see that hex code represents a string.
73-74-75-64-65-6E-74-41-73-73-69-67-6E-6D-65-6E-74 decoded is studentAssignment
This leads me to believe you are doing a simple AJAX call and sending JSON data to WebAPI service.
You need to deserialize the stream using JSON.
Read request content as string
If content is JSON, deserialize it using JSON.NET
var json = actionContext.Request.Content.ReadAsStringAsync().Result;
var m = JsonConvert.DeserializeObject<EvaluationFormDataContract>(json);
If response is not JSON, but form data you can parse it like a query string.
var stringData = actionContext.Request.Content.ReadAsStringAsync().Result;
NameValueCollection data = HttpUtility.ParseQueryString(stringData);
string personId = data["personId"];

Related

POST Web Service Client using C#

Can you please give me a sample example of how to make the JSON request body in C#. I am using Visual Studio 2015. I know SOAP UI, but I am new to C#.
Thanks in advance.
You can try the following
Lets assume you have the following webmethod
public void Webmethod(string parameter)
{
//Do what ever
}
In C# you will do the following to call the webmethod, You require Json.net, Newtonsoft or other Json serializer
var webRequest = WebRequest.Create("http:\\www.somesite.com/path/to/webservice/webservice.asmx/Webmethod");
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
Build a Json object representing the parameters
var jsonobjectrepresentingparameters = new {parameter = "Value"};
Get the Json string using Newtonsoft JsonConvert
var datastring = Newtonsoft.Json.JsonConvert.SerializeObject(jsonobjectrepresentingparameters);
Get the bytes
var bytes = Encoding.ASCII.GetBytes(datastring);
Write the bytes to the request
var requestStream = webRequest.GetRequestStream();
requestStream.Write(bytes, 0,bytes.Length);
Get repsonse
var response = webRequest.GetResponse();
If your Webmethod returned anything like a string, int or other data you can use the following class to deserialize
public class Type<T>
{
public T D { get; set; }
public Type()
{
}
}
You will notice when you work with webservices it returns a json object with property d as the value which is why you require the above class in C#
Then you will require the following extra two lines if your return type was string
var json = (new StreamReader(response.GetResponseStream())).ReadToEnd();
var object = JsonConvert.DeserializeObject<Type<string>>(json);

Deserializing JSON List object

I receive this JSON object from a web request:
"\"[{\\\"EventId\\\":25,\\\"StartDate\\\":\\\"2014-06-12T12:00:00\\\",\\\"EndDate\\\":\\\"2014-06-17T12:00:00\\\",\\\"Title\\\":\\\"Test\\\",\\\"Description\\\":\\\"desc\\\",\\\"Teaser\\\":\\\"teaser\\\",\\\"PhoneNumber\\\":null,\\\"Email\\\":null,\\\"AddressOne\\\":null,\\\"AddressTwo\\\":null,\\\"City\\\":null,\\\"State\\\":null,\\\"ZipCode\\\":null,\\\"Country\\\":null,\\\"RegistrationUrl\\\":null,\\\"CreatedBy\\\":\\\"c216cd34-6a3d-4f38-950b-ea3383a30a64\\\"},{\\\"EventId\\\":25,\\\"StartDate\\\":\\\"2014-06-13T12:00:00\\\",\\\"EndDate\\\":\\\"2014-06-18T12:00:00\\\",\\\"Title\\\":\\\"Test\\\",\\\"Description\\\":\\\"desc\\\",\\\"Teaser\\\":\\\"teaser\\\",\\\"PhoneNumber\\\":null,\\\"Email\\\":null,\\\"AddressOne\\\":null,\\\"AddressTwo\\\":null,\\\"City\\\":null,\\\"State\\\":null,\\\"ZipCode\\\":null,\\\"Country\\\":null,\\\"RegistrationUrl\\\":null,\\\"CreatedBy\\\":\\\"c216cd34-6a3d-4f38-950b-ea3383a30a64\\\"},{\\\"EventId\\\":25,\\\"StartDate\\\":\\\"2014-06-14T12:00:00\\\",\\\"EndDate\\\":\\\"2014-06-19T12:00:00\\\",\\\"Title\\\":\\\"Test\\\",\\\"Description\\\":\\\"desc\\\",\\\"Teaser\\\":\\\"teaser\\\",\\\"PhoneNumber\\\":null,\\\"Email\\\":null,\\\"AddressOne\\\":null,\\\"AddressTwo\\\":null,\\\"City\\\":null,\\\"State\\\":null,\\\"ZipCode\\\":null,\\\"Country\\\":null,\\\"RegistrationUrl\\\":null,\\\"CreatedBy\\\":\\\"c216cd34-6a3d-4f38-950b-ea3383a30a64\\\"},{\\\"EventId\\\":25,\\\"StartDate\\\":\\\"2014-06-15T12:00:00\\\",\\\"EndDate\\\":\\\"2014-06-20T12:00:00\\\",\\\"Title\\\":\\\"Test\\\",\\\"Description\\\":\\\"desc\\\",\\\"Teaser\\\":\\\"teaser\\\",\\\"PhoneNumber\\\":null,\\\"Email\\\":null,\\\"AddressOne\\\":null,\\\"AddressTwo\\\":null,\\\"City\\\":null,\\\"State\\\":null,\\\"ZipCode\\\":null,\\\"Country\\\":null,\\\"RegistrationUrl\\\":null,\\\"CreatedBy\\\":\\\"c216cd34-6a3d-4f38-950b-ea3383a30a64\\\"},{\\\"EventId\\\":25,\\\"StartDate\\\":\\\"2014-06-16T12:00:00\\\",\\\"EndDate\\\":\\\"2014-06-21T12:00:00\\\",\\\"Title\\\":\\\"Test\\\",\\\"Description\\\":\\\"desc\\\",\\\"Teaser\\\":\\\"teaser\\\",\\\"PhoneNumber\\\":null,\\\"Email\\\":null,\\\"AddressOne\\\":null,\\\"AddressTwo\\\":null,\\\"City\\\":null,\\\"State\\\":null,\\\"ZipCode\\\":null,\\\"Country\\\":null,\\\"RegistrationUrl\\\":null,\\\"CreatedBy\\\":\\\"c216cd34-6a3d-4f38-950b-ea3383a30a64\\\"}]\""
I have an object that matches this type called EventView and deserialize it into an object like so:
string result = "";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
JavaScriptSerializer jss = new JavaScriptSerializer();
JsonEventView ev = jss.Deserialize<JsonEventView>(result);
public class JsonEventView
{
public List<EventView> results { get; set; }
}
However, I get an error every time I attempt to deserialize it.
Cannot convert object of type 'System.String' to type 'EventManagerService.JsonEventView'
Web API handles the serialization for you. So you do not need to manually serialize the object to JSON.
return Request.CreateResponse(HttpStatusCode.OK, Active);
Of course, Web API being able to return JSON hinges on Content Negotiation and your app being properly configured, such that there is a formatter that can provide the output a consumer requests (JSON in this case).

Return json without binding it to object using web client

I want to simply return a JsonResult in C# from an online API service (iTunes). What I am wanting to do is just go out get the data in JSON format and return that exact data in the same JSON format so I can play with it in javascript.
Here is what I have:
public JsonResult Index()
{
using (var client = new WebClient())
{
var json = client.DownloadString("https://itunes.apple.com/lookup?id=909253");
return json;
}
}
I am noticing I can't return the json because it is now a string. I don't want to bind this to a model!!! I just want to return a JSON object exactly how I got it.
Change your method signature to return a string instead of a JsonResult object…
public string Index()
{
using (var client = new WebClient())
{
return client.DownloadString("https://itunes.apple.com/lookup?id=909253");
}
}
Already given answer is ok to get json in javascript.. javasript will treat this string same as if your return json object..
However if you have to get a json object from string in c# anyway then check the accepted answer here
Parse JSON String to JSON Object in C#.NET

How can i send an XML file as an object to some other function

I needed to read(load) one xml file, and send the same file as an object to other function. Here the problem I am facing is, while loading the file, it is converted to XML Object. Now we can get the details of the file by accessing the InnerXML property, where it got converted to String.
How can I get this String object get assigned to an normal Object whose properties are internally similar to this xml?
See the sample:
SearchResponse Response = new SearchResponse();
XmlDocument doc = new XmlDocument();
doc.Load(#"C:\Search_Response.xml");
Object response = new Object();
response = doc.InnerXml;
Response = (SearchResponse)response;
return Response;
Please help me out!
You can achieve this by Serialization.
use Microsoft.Http.HttpClient. This will give you to convert Xml to Object Very easily.
Eg:
SearchResponse Response = new SearchResponse();
var client = new HttpClient();
var httpResponseMessage = client.Get(uri);
Response = httpResponseMessage.Content.ReadAsXmlSerializable<SearchResponse >();

Deserialise an xml representation of a string and primitive type - ASP.NET Web API

I am currently implementing a web service with the ASP.net Web API and one of my methods returns a string. The problem is it returns the string like this:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization">Some Resource</string>
This kind of response is what I want, but I don't know how to deserialise it in my web service client.
How would you deserialise any xml representing a string or any primitive datatype?
Thanks!
You can use ReadAsAsync from the System.Net.Http.Formatting.dll. Say
'uri' will get me this data:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
Some Resource
</string>
Then you can use ReadAsAsync to get the string in the XML:
HttpClient client = new HttpClient();
var resp = client.GetAsync(uri).Result;
string value = resp.Content.ReadAsAsync<string>().Result;
(I'm calling .Result directly to demonstrate the use of ReadAsAsync<> here...)
// Convert the raw data into a Stream
string rawData = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Some Resource</string>";
MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(rawData));
// User DataContractSerializer to deserialize it
DataContractSerializer serializer = new DataContractSerializer(typeof(string));
string data = (string)serializer.ReadObject(stream);
Console.WriteLine(data);

Categories

Resources