csharp MVC操作筛选器允许上载安全文件属性

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp MVC操作筛选器允许上载安全文件属性相关的知识,希望对你有一定的参考价值。

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);
        }
    }
}

以上是关于csharp MVC操作筛选器允许上载安全文件属性的主要内容,如果未能解决你的问题,请参考以下文章

csharp 验证操作筛选器作为控制器操作属性将在视图模型验证失败时返回错误请求

csharp 一个过滤器属性,允许您将ASP.NET MVC视图下载为Word文档

上载文件筛选器

MVC和Web API 过滤器Filter [转]

csharp 这为mvc创建了一个新的操作链接扩展,用于检查用户的声明并允许在声明有效时显示链接o

csharp ssh.net示例 - 基于密钥的身份验证,文件上载,Shell命令