6

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

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

4

1 回答 1

8

您可以从 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)
    }
}
于 2012-09-04T09:09:55.553 回答