6

I want to validate the file extension of file uploads in ASP.NET Web API (note: I realize that this is not a full-proof method of validation).

I'm using the MultipartFormDataStreamProvider to process the POSTed file. Since Request.Content.Headers.ContentDisposition is null before the provider processes the file (via ReadAsMultipartAsync), where is the best place to validate the file name of the request?

Ben Foster
  • 34,340
  • 40
  • 176
  • 285

1 Answers1

8

You can inherit from MultipartFormDataStreamProvider and override either GetLocalFileName (runs after reading content into stream) or GetStream (runs prior to reading content into the stream). In both cases you have access to 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)
    }
}
Filip W
  • 27,097
  • 6
  • 95
  • 82