I have an MVC controller action to which I am posting a file stream: -
public ActionResult Upload()
{
try
{
HttpPostedFileBase files = Request.Files[0];
Stream fileStream = files.InputStream;
String url = ConfigurationManager.AppSettings[ConfigurationParams.ServiceGatewayURI];
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.AllowWriteStreamBuffering = false;
request.Timeout = 86400000;
request.ContentType = "application/json";
request.ContentLength = fileStream.Length;
Stream outputStream = request.GetRequestStream();
int BYTELENGTH = 1024;
byte[] chunk = new byte[BYTELENGTH];
while (fileStream.Position < fileStream.Length)
{
int len = fileStream.Read(chunk, 0, BYTELENGTH);
outputStream.Write(chunk, 0, len);
}
fileStream.Close();
fileStream.Dispose();
outputStream.Close();
outputStream.Dispose();
return Json("");
}
catch (Exception ex)
{
return Json(new { error = String.Format("Exception when streaming to back end, {0}"),ex.Message });
}
}
The inputStream is then POSTed to an API controller method as per the address in the url variable. The stream is then then saved to disk via another method for the object context.
API controller method: -
public String Post(string documentName)
{
return context.SaveFile(documentName, Request.Content.ReadAsStreamAsync().Result);
}
public string SaveFile(documentName, Stream inputStream)
{
// Exception happens here!
}
The challenge I am facing is that when an exception happens in the SaveFile method, it does not flow back up to the Upload controller call. The Upload controller remains blissfully unaware that something went wrong when saving the file.
I can see two separate streams when debugging with Fiddler, including an HTTP 500 error from the SaveFile method.
My question is how can I throw an exception from the SaveFile method to the Upload controller? I have tried closing the inputStream on the back end when an exception is raised, but that did not return a 500 for the Upload call.
Thanks.