asp.net – 如何从System.Web.HttpPostedFileBase转换为System.Web.HttpPostedFile?

在Scott Hanselman博客上尝试实现一个MVC文件上传 example.我遇到了这个示例代码的麻烦:
foreach (string file in Request.Files)
{
   HttpPostedFile hpf = Request.Files[file] as HttpPostedFile;
   if (hpf.ContentLength == 0)
      continue;
   string savedFileName = Path.Combine(
      AppDomain.CurrentDomain.BaseDirectory,Path.GetFileName(hpf.FileName));
   hpf.SaveAs(savedFileName);
}

我把它转换成VB.NET:

For Each file As String In Request.Files
    Dim hpf As HttpPostedFile = TryCast(Request.Files(file),HttpPostedFile)
    If hpf.ContentLength = 0 Then
        Continue For
    End If
    Dim savedFileName As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,Path.GetFileName(hpf.FileName))
    hpf.SaveAs(savedFileName)
Next

但是我从编译器得到一个无效的转换异常:

Value of type 'System.Web.HttpPostedFileBase' cannot be converted to 'System.Web.HttpPostedFile'.

汉斯曼在2008-06-27发布了他的例子,我认为它在当时工作. MSDN没有任何类似的例子,所以给出了什么?

解决方法

只需使用它作为一个HttpPostedFileBase.该框架使用HttpPostedFileWrapper将HttpPostedFile转换为HttpPostedFileBase的对象. HttpPostedFile是那些难以单元测试的密封类之一.我怀疑在写了例子之后,他们应用了包装代码来提高在MVC框架中测试(使用HttpPostedFileBase)控制器的能力.控制器上的HttpContext,HttpRequest和HttpReponse属性已经完成了类似的操作.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....