我正在开发一个多级ASP.NET MVC Web平台,我需要将文件从System.Web.Mvc.Controller
发送到ASP.NET MVC Web服务的System.Web.Http.ApiController
,远程运行在另一台机器上。
目前,我在Mvc.Controller
:
public ActionResult ForwardThisFile(HttpPostedFileBase file)
{
// TODO: Forward file to remote DocumentApi:
DocumentApi.DocumentApiClient client = new DocumentApi.DocumentApiClient();
client.StoreDocument(file /* <-- How-To? */);
return View();
}
其中DocumentApiClient
已通过Visual Studio的添加REST API客户端... 函数从Swagger URL生成。 (生成的客户端内部使用依赖Microsoft.Rest.ClientRuntime
,System.Net.Http.HttpClient
等的HttpRequestMessage
。
问题是,我如何定义和实现DocumentApi,以便在ApiController
中以高效通用的方式将文件传输给它。目前,我正在考虑三种不同的选择:
[HttpPut] public async Task<IHttpActionResult> StoreDocument(HttpPostedFileBase file)
[HttpPut] public async Task<IHttpActionResult> StoreDocument(byte[] fileContents, string contentType, string fileName)
[HttpPut] public async Task<IHttpActionResult> StoreDocument(Stream fileStream, string contentType, string fileName)
我在想,也许我可以将HttpPostedFileBase
实例从Mvc.Controller
转发到ApiController
,所以我尝试了第一个选项。但是,在这种情况下,添加REST API客户端... 会创建一个DocumentApi.Models.HttpPostedFileBase
模型类,而不是原始类型System.Web.HttpPostedFileBase
。现在,我不确定我应该做什么......
new DocumentApi.Models.HttpPostedFileBase() {
InputStream = file.InputStream,
ContentType = file.ContentType,
ContentLength = file.ContentLength,
FileName = file.FileName,
}
^不起作用,因为对于InputStream
,它会创建一个DocumentApi.Models.Stream
类,我不知道如何从System.IO.Stream
参数转换file
进入DocumentApi.Models.Stream
。
甚至可以跨ASP.NET MVC webservices发送流吗? (这基本上是选项3的答案)
在我目前的知识状态中,唯一的替代选择在我看来是选项2,在那里我将发送一个包含整个文件的字节数组。但是,我问自己,是否有更方便或更有效的方式将文件从Mvc.Controller
发送到远程ApiController
。有吗?
哪一个选项可行,哪一个是可行的方法?
此外,我对上述HttpPostedFileBase
有一个加分问题:通过HttpPostedFileBase
处理ASP.NET MVC中上传文件的最有效方法是什么?我见过各种替代方案:
HttpPostedFileBase
如上面第一个代码示例所示Request.Content.ReadAsStreamAsync()
或类似的东西使用原始HTTP请求。也许这个流对我的用例更有效?FileReader
的方法readAsDataURL(file)
)这么多选项......哪一个最好/最通用/最有效?
答案 0 :(得分:0)
您应该使用调用控制器中的HttpClient lib来异步将文件上载到目标控制器。使用HttpClient进行asycn上传的各种示例都在C# HttpClient 4.5 multipart/form-data upload。
在这种情况下,您的接收遥控器就像是从浏览器上传文件而不需要特定处理。