I would like some advice on the best way to transfer custom objects from a "REST" server to a controller. In brief, we are running MVC 4 on a server that handles HttpGet
requests. Initially, all responses from the server could be accommodated by serializing our custom classes to JSON and then deserializing them client size. However, now that we need to transfer large data (i.e. images) this approach no longer works.
The followings is condensed versions of what I am currently doing, but I would like some advice on a better way to transfer large files (custom types).
classes:
[Serializable]
public class TradingPost
{
public int TradingPostId { get; set; }
public string UserId { get; set; }
}
[Serializable]
public class TradingPostImage
{
public int TradingPostImageId { get; set; }
public string ImageName { get; set; }
public string ImageData { get; set; }
}
[Serializable]
public class TradingPostWithImages
{
public TradingPost Post { get; set; }
public List<TradingPostImage> Images { get; set; }
public TradingPostWithImages()
{
Post = new TradingPost();
Images = new List<TradingPostImage>();
}
}
Server side controller:
[HttpGet]
public ActionResult GetAllTradingPosts()
{
List<TradingPostWithImages> postsAndImages = PostRepository.GetAllPostsAndImages();
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, postsAndImages);
var postsAsByteArray = memoryStream.ToArray();
return File(postsAsByteArray, "application/octet-stream");
}
Client side controller:
public List<TradingPostWithImages> GetItems()
{
var dataGatewayPath = GetGateWayPath("GetTradingPosts");
MemoryStream webData = new MemoryStream();
var Request = WebRequest.CreateHttp(dataGatewayPath );
var Response = Request.GetResponse() as HttpWebResponse;
if(Response != null)
{
DataStream = Response.GetResponseStream();
if(DataStream != null)
{
DataStream.CopyTo(webData);
DataStream.Close();
}
Response.Close();
}
webData.Position = 0;
BinaryFormatter formatter = new BinaryFormatter();
var activeItems = (List<TradingPostWithImages>)formatter.Deserialize(webData);
return activeItems;
}
This works, but is there a way I can accomplish what I am after without deserializing a stream and then casting it to my custom type? Is there a better, or more efficient way to accomplish my task?