如何在ASP.NET Web API中验证文件上载

时间:2012-09-04 08:29:36

标签: asp.net-web-api

我想在ASP.NET Web API中验证文件上传的文件扩展名(注意:我意识到这不是一种完全验证的验证方法)。

我正在使用MultipartFormDataStreamProvider来处理POSTed文件。由于Request.Content.Headers.ContentDisposition在提供程序处理文件之前为空(通过ReadAsMultipartAsync),验证请求文件名的最佳位置在哪里?

1 个答案:

答案 0 :(得分:7)

您可以从MultipartFormDataStreamProvider继承并覆盖GetLocalFileName(在将内容读入流后运行)或GetStream(在将内容读入流之前运行)。在这两种情况下,您都可以访问headers.ContentDisposition.FileName

public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    public CustomMultipartFormDataStreamProvider(string path)
        : base(path)
    {
    }

    public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
    {
        //validate headers.ContentDisposition.FileName as it will have the name+extension
        //then do something (throw error, continue with base or implement own logic)
    }

    public override Stream GetStream(HttpContent parent, System.Net.Http.Headers.HttpContentHeaders headers)
    {
        //validate headers.ContentDisposition.FileName as it will have the name+extension

        //then do something (throw error, continue with base or implement own logic)
    }
}