找不到类型为“System.Web.HttpPostedFile”的构造函数

时间:2009-12-17 12:47:10

标签: c# asp.net reflection

我正在尝试使用

创建HttpPostedFile的实例
var obj2 = Activator.CreateInstance(
    typeof(HttpPostedFile), 
    BindingFlags.NonPublic | BindingFlags.Instance,
    null,
    new object[] { },
    System.Globalization.CultureInfo.CurrentCulture
);

但是我收到错误'类型'上的构造函数'找不到System.Web.HttpPostedFile。'。

是否有其他方法可以创建HttpPostedFile实例,或者我做错了什么?

4 个答案:

答案 0 :(得分:5)

我遇到了同样的问题,并使用Moq解决了以下问题

var postedfile = new Mock<HttpPostedFileBase>();
postedfile.Setup(f => f.ContentLength).Returns(8192);
postedfile.Setup(f => f.FileName).Returns("myfile.txt");
postedfile.Setup(f => f.InputStream).Returns(new MemoryStream(8192));
myObject.HttpPostedFile = postedfile.Object;

答案 1 :(得分:4)

您可以使用System.Web.HttpPostedFileBase代替。这与HttpPostedFile具有相同的方法,但设计用于子类。然后,您可以使用HttpPostedFileWrapper将实际HttpPostedFile传递给期望HttpPostedFileBase的方法。

这些额外的类位于System.Web.Abstractions程序集中。 ASP.NET MVC利用这个(以及同一程序集中的其他抽象)来简化单元测试。有关详细信息,请参阅the documentation on MSDN

答案 2 :(得分:2)

HttpPostedFile有一个内部构造函数,它带有3个参数,并不打算从你的代码中调用:

internal HttpPostedFile(string filename, string contentType, HttpInputStream stream)

为了实例化这个类,你需要传递一个文件名,一个内容类型和一个同样是内部类型的HttpInputStream实例,所以实例化它的唯一方法是通过反射。

答案 3 :(得分:0)

HttpPostedFile不公开公共构造函数,它可以通过文件上传控件使用。

我认为你应该使用其他类,那么你究竟想用HttpPostedFile做什么?