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

Asp.net 如何从System.Web.HttpPostedFileBase转换为System.Web.HttpPostedFile?,asp.net,asp.net-mvc,vb.net,Asp.net,Asp.net Mvc,Vb.net,试图在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( AppDo

试图在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);
}
我将其转换为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'.

Hanselman在2008-06-27上发布了他的例子,我想当时它是有效的。MSDN没有任何类似的示例,因此给出了什么?

正确的使用类型是HttpPostedFileBase

HttpPostedFileBase hpf = Request.Files[file];

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

其他信息:如果您像我一样,在单独的项目中创建此函数,则必须包含System.Web.Abstractions.dll文件,以便引用HttpPostedFileBase per:@tvanfosson我正在查找此信息,为什么要使用HttpPostedFileBase而不是HttpPostedFile?您有可以共享的链接吗?@codingbiz这是因为您可以模拟HttpPostedFileBase类进行单元测试。模拟框架通常会阻塞模拟密封类,因为它们使用继承来创建模拟。是否还有其他类继承自HttpPostedFileBase?根据这个名称,它应该是由其他类继承的抽象类?我试着将它转换到HttpPostedFile中,但没有通过。我认为这个名字有误导性:使您假定HttpPostedFile源于HttpPostedFileBase@codingbiz我相信只有HttpPostedFileWrapper从它派生出来。“基类”和包装器是在HttpPostedFile之后出现的,旨在“纠正”MVC(以及更高版本)中的可测试性问题?我想进一步了解一下HttpPostedFileBase和HttpPostedFile之间的区别。