WCF Image Serialization

I have this code in my WCF service:

public class MyImage { public Image Image { get; set; } public string FullPath { get; set; } } [ServiceContract] public interface IMyService { [OperationContract] void SaveImage(MyImage myImg); } public class MyService : IMyService { public void SaveImage(MyImage myImg) { // ... } } 

But this error occurs when I run the SaveImage () method:

An error occurred while trying to serialize the http://tempuri.org/:e parameter. The InnerException message was " Type" System.Drawing.Bitmap "with the data contract name" Bitmap: http://schemas.datacontract.org/2004/07/System.Drawing "is not expected ... using DataContractResolver or add any types that are not known statically to the list of known types - for example, using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer. '

My code is in C #, Framework 4.0, in Visual Studio 2010 Pro.

Please help, thanks in advance.

+4
source share
2 answers

The expected "data contract" is Image , but it received an instance of Bitmap : Image . WCF loves to know about inheritance in advance, so you will need to talk about it. But! I honestly don't think this is a good approach; you should just simply throw away the raw binary, which probably means first storing the Image in a MemoryStream . You should also formally decorate your type of contract. I would send:

 [DataContract] public class MyImage { [DataMember] public byte[] Image { get; set; } [DataMember] public string FullPath { get; set; } } 

An example of getting byte[] :

 using(var ms = new MemoryStream()) { image.Save(ms, ImageFormat.Bmp); return ms.ToArray(); } 
+14
source

As you can read here: You need to serialize the silverlight bitmap . Image is not serializable. Thus, you can turn the image into an array of bytes (of any format you like, from simple pixel colors to the official format, such as PNG) and use it

+1
source

Source: https://habr.com/ru/post/1393098/


All Articles