feanz
4/2/2014 - 10:30 AM

MVC Action Filter Allow upload of safe files attribute

MVC Action Filter Allow upload of safe files attribute

using  System;
using  System.linq;
using  System.collections.generic;
using  System.IO;
using  System.web.mvc;
 
namespace  Securitymodule
{
    [Attributeusage (Attributetargets.method, Allowmultiple = false )]
    public  sealed  class  Allowuploadsafefilesattribute: Actionfilterattribute
    {
        static  readonly  IList < string > Exttofilter = new  List < string > {
            ". Aspx" , ". Asax" , ". asp" , ". Ashx" , ". aspx," , ". Axd" , ". master" , ". svc" , ". php"  ,        
            ". Php3"  , ". php4" , ". Ph3" , ". Ph4" , ". php4" , ". Ph5" , ". Sphp" , ". cfm" , ". ps" , ". Stm" ,
            ". Htaccess" , ". Htpasswd" , ". php5" , ". Phtml" , ". cgi" , ". pl" , ". Plx" , ". py" , ". rb" , ". sh" , ". jsp" ,
            ". Cshtml" , ". Vbhtml" , ". swf"  , ". Xap" , ". Asptxt"
        };
 
        static  readonly  IList < string > Nametofilter = new  List < string > {
           "Web.config"  , "htaccess"  , "Htpasswd" , "web ~ 1.con"
        };
 
        static  bool  Canupload ( string  fileName)
        {
            if  ( string . Isnullorwhitespace (fileName))
                return  false ;
 
            fileName = fileName.ToLowerInvariant ();
            var name = Path.GetFileName (fileName);
            var ext = Path.GetExtension (fileName);
 
            if  ( string . Isnullorwhitespace (name))
                throw  new  InvalidOperationException ( "Uploaded file should have a name." );
 
            return  ! Exttofilter.contains (ext) &&
                   ! NameToFilter.Contains (name) &&
                   ! NameToFilter.Contains (ext) &&
                   / / For "file.asp;. Jpg" files
                   ExtToFilter.All (item =>! Name.Contains (item));
        }
 
        public  override  void  Onactionexecuting (Actionexecutingcontext Filtercontext)
        {
            var files = filterContext.HttpContext.Request.Files;
            foreach  ( string  file in  files)
            {
                var postedFile = files [file];
                if  (Postedfile == null  | | Postedfile.contentlength == 0) continue ;
 
                if  (! Canupload (Postedfile.filename))
                    throw  new  InvalidOperationException ( string . Format ( "You are not allowed to upload file {0}." , Path.getfilename (Postedfile.filename)));
            }
 
            base . Onactionexecuting (Filtercontext);
        }
    }
}