Reputation: 3018
My class is
[Serializable]
public class Class1 : ISerializable
{
public int Id { get; set; }
public string Name { get; set; }
public Class1() { }
Class1(SerializationInfo info, StreamingContext context)
{
Id = (int)info.GetValue(nameof(Id), typeof(int));
Name = (string)info.GetValue(nameof(Name), typeof(string));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(nameof(Id), Id);
info.AddValue(nameof(Name), Name);
}
public override string ToString()
{
return $"{Id}; {Name}";
}
}
My Web API serializes this class then sends as byte array;
public class DataController : ApiController
{
public byte[] Get()
{
Class1 class1 = new Class1()
{
Id = 100,
Name = "Name"
};
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, class1);
return memoryStream.ToArray();
}
}
}
In my WinForms application I am trying to get this serialized class and resurrect it,
private async void Button1_Click(object sender, EventArgs e)
{
HttpClient httpClient = new HttpClient();
Uri uri = new Uri(textBox1.Text);
var bytes = await httpClient.GetByteArrayAsync(uri);
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream(bytes))
{
var class1 = binaryFormatter.Deserialize(memoryStream) as Class1;
richTextBox1.Text = class1.ToString();
}
}
But the method Deserialize
is throwing an exception saying "The input stream is not a valid binary format."
What am I doing wrong?
Upvotes: 1
Views: 627
Reputation: 3018
I wanted to exchange an object between the server and client. Somehow I did it in a wrong way. First of all, there is no need to serialize the object manually. What we need is to send the object directly, not its serialized bytes. ASP.NET MVC takes care of serialization for us, according to my understanding. So, the API method should be
public Class1 Get()
{
return new Class1()
{
Id = 100,
Name = "Name"
};
}
There is a package called Microsoft.AspNet.WebApi.Client
which ads support for formatting and content negotiation to System.Net.Http
. The assembly called System.Net.Http.Formatting
, a part of the package, does both serialization and deserialization. When we create a new web application, Visual Studio installs this package automatically into the project.
However, for Windows Forms
project it must be manually installed via NuGet package manager. The package installation will add 2 assemblies to the project, Newtonsoft.Json
and System.Net.Http.Formatting
. Then, the rest is very simple
private void GetButton_Click(object sender, EventArgs e)
{
HttpClient httpClient = new HttpClient();
Uri uri = new Uri(textBox1.Text);
var content = httpClient.GetAsync(uri).Result.Content;
var class1 = content.ReadAsAsync<Class1>().Result;
richTextBox1.Text = class1.ToString();
}
And Bob's your uncle!!!
Upvotes: 1