开发者

Constructor on type 'System.Web.HttpPostedFile' not found

I'm trying to create an instance of HttpPostedFile with

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

but I'm getting the error 'Constructor on type 'System.Web.HttpPostedF开发者_StackOverflow社区ile' not found.'.

Is there another way to create an instance of HttpPostedFile or am I doing something wrong?


I've just had the same problem and solved it using Moq as follows

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;


You might be able to use System.Web.HttpPostedFileBase instead. This has the same methods as HttpPostedFile but is designed for sub-classing. You can then use HttpPostedFileWrapperto pass in a real HttpPostedFile to a method expecting an HttpPostedFileBase.

These extra classes are in the System.Web.Abstractions assembly. ASP.NET MVC makes use of this (and other abstractions in the same assembly) to make unit testing easier. See the documentation on MSDN for more information.


HttpPostedFile has an internal constructor that takes 3 arguments and that is not intended to be called from your code:

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

In order to instantiate this class you will need to pass a filename, a content type and a HttpInputStream instance which is a type that is also internal so the only way to instantiate it is through reflection.


HttpPostedFile does not expose public constructors, it's available with the file upload control.

I think you should use some other class, so what exactly are you trying to do with the HttpPostedFile?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜