问题
I'm making a call to an MVC controller method. The return type is FileStreamResult. In this method I'm creating an image in the form of a byte array. I'm creating a MemoryStream, passing the byte array in the constructor. I'm then returning a new FileStreamResult object with the memory stream object and "image/png" in the constructor, as my image is a PNG.
public FileStreamResult GetImage()
{
ImageModel im = new ImageModel();
var image = im.GetImageInByteArray();
var stream = new MemoryStream(image);
return new FileStreamResult(stream, "image/png");
}
Now, when I get the request stream from this call, I'm simply using the following method to convert the stream string into a byte array to view the image. However, after this is all done, I end up with 100+ more positions in my byte array than when I return from the MVC controller method call.
public static byte[] ConvertStringToBytes(string input)
{
MemoryStream stream = new MemoryStream();
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(input);
writer.Flush();
}
return stream.ToArray();
}
For example, after the "GetImageInByteArray()" call, I have "byte[256]". But when it returns from that MVC call and I convert the response string by putting it through the second method, I end up with "byte[398]";
EDIT QUESTION Is there some kind of divide between the web request I'm making to the GetImage() controller method and what I assume I'm receiving?
I assume what I'm receiving from that call is the memory stream of the image byte array. This is why I'm simply converting that back to a byte array.
Is my assumption here wrong?
回答1:
When an MVC action returns a result, it goes through the ASP.NET pipeline which tacks on HTTP headers so that the requestor (browser) can understand what to do with the response.
For an image, these headers might include:
Response Code
Content-Length
Content-Type
Or any other number of custom or typical HTTP headers (Some more HTTP Headers).
If I understand your question correctly, you're converting the entire response from your action to bytes, so naturally, you'll also be converting the headers and anything else the request might return (cookies?).
What are you trying to accomplish with deserialization of the request? Are you trying to test something?
回答2:
How is your string encoded ? In my opinion it is a problem with encoding.
Try this as your method code:
return (new System.Text.UTF8Encoding()).GetBytes(input);
Greetings
回答3:
I really appreciate your help Dawid, but I decided to simply go another way. I created a transfer object to simply hold the byte array as a property. I serialize this, then pass the object across, deserialize on the opposite end and I have my byte array as it was.
I still am confused on what the HTTP request was tacking onto the memory stream that was being passed, but I just went another route.
来源:https://stackoverflow.com/questions/5277620/asp-net-mvc-filestreamresult-returning-too-many-bytes