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?

1 Answer 1

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)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.