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

Jim*_*nts 13 vb.net asp.net asp.net-mvc

在尝试在Scott Hanselman的博客上实现MVC文件上传示例时.我遇到了这个示例代码的问题:

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);
}
Run Code Online (Sandbox Code Playgroud)

我把它转换为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
Run Code Online (Sandbox Code Playgroud)

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

Value of type 'System.Web.HttpPostedFileBase' cannot be converted to 'System.Web.HttpPostedFile'.
Run Code Online (Sandbox Code Playgroud)

Hanselman在2008-06-27发布了他的例子,我认为它当时有效.MSDN没有任何类似的例子,那么给出了什么?

tva*_*son 27

只需将其作为HttpPostedFileBase使用即可.该框架使用HttpPostedFileWrapper将HttpPostedFile转换为HttpPostedFileBase的对象.HttpPostedFile是难以进行单元测试的密封类之一.我怀疑在编写示例之后的某个时候,他们应用了包装器代码来提高在MVC框架中测试(使用HttpPostedFileBase)控制器的能力.在控制器上使用HttpContext,HttpRequest和HttpReponse属性也做了类似的事情.

  • 附加信息:如果您和我一样,并且您在单独的项目中创建此功能,则必须包含System.Web.Abstractions.dll文件,以便引用HttpPostedFileBase:http://efreedom.com/Question/ 1-1911151/CSHARP引用-HttpPostedFileBase (2认同)