我有一个MVC控制器操作,我发布了一个文件流: -
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 });
}
}
然后根据url变量中的地址将inputStream POST到API控制器方法。然后通过另一个对象上下文方法将流保存到磁盘。
API控制器方法: -
public String Post(string documentName)
{
return context.SaveFile(documentName, Request.Content.ReadAsStreamAsync().Result);
}
public string SaveFile(documentName, Stream inputStream)
{
// Exception happens here!
}
我面临的挑战是,当SaveFile方法发生异常时,它不会回流到上传控制器调用。保存文件时,上传控制器仍然没有意识到出现了问题。
在使用Fiddler进行调试时,我可以看到两个独立的流,包括来自SaveFile方法的HTTP 500错误。
我的问题是如何将SaveFile方法中的异常抛出到Upload控制器?我曾尝试在引发异常时关闭后端的inputStream,但是没有为Upload调用返回500.
感谢。