无法将类型'System.Web.HttpPostedFile'隐式转换为'System.Web.HttpPostedFileBase'

tom*_*tom 14 asp.net

我有这个不构建的方法,它与消息错误:

无法隐式将类型' System.Web.HttpPostedFile' 转换为' System.Web.HttpPostedFileBase'

我真的需要这个类型HttpPostedFileBase而不是HttpPostedFile,我尝试拳击,它不起作用:

foreach (string inputTagName in HttpContext.Current.Request.Files)
{
    HttpPostedFileBase filebase =HttpContext.Current.Request.Files[inputTagName];
    if (filebase.ContentLength > 0)
    {
        if (filebase.ContentType.Contains("image/"))
        {
         SaveNonAutoExtractedThumbnails(doc, filebase);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*sch 25

快速浏览一下Reflector,表明它在构造函数中HttpPostedFileWrapper继承HttpPostedFileBase并接受HttpPostedFile:

foreach (string inputTagName in HttpContext.Current.Request.Files)
{
    HttpPostedFileBase filebase = 
      new HttpPostedFileWrapper(HttpContext.Current.Request.Files[inputTagName]);

    if (filebase.ContentLength > 0)
    {
        //...
Run Code Online (Sandbox Code Playgroud)

TheVillageIdiot提出了关于更好的循环结构的一个很好的观点,如果你的范围暴露Request了当前HTTP上下文的属性(例如,在a Page,但不在其中Global.asax),它将对你有用:

foreach (HttpPostedFile file in Request.Files)
{
    HttpPostedFileBase filebase = new HttpPostedFileWrapper(file);
    // ..
Run Code Online (Sandbox Code Playgroud)

如果您有LINQ可用,您也可以使用它:

var files = Request.Files.Cast<HttpPostedFile>()
                .Select(file => new HttpPostedFileWrapper(file))
                .Where(file => file.ContentLength > 0 
                            && file.ContentType.StartsWith("image/"));

foreach (var file in files)
{
    SaveNonAutoExtractedThumbnails(doc, file);
}
Run Code Online (Sandbox Code Playgroud)