How to check file upload in ASP.NET Web API

I want to check the file upload file extension in the ASP.NET Web API (note: I understand that this is not a complete verification method).

I use MultipartFormDataStreamProviderto process the POSTed file. Since Request.Content.Headers.ContentDispositionit is null before the provider processes the file (via ReadAsMultipartAsync), where is the best way to check the name of the request file?

+5
source share
1 answer

You can inherit from MultipartFormDataStreamProvider and override either GetLocalFileName (launched after reading the contents of the stream) or GetStream (executed before reading the contents of the stream). In both cases, you have access toheaders.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)
    }
}
+7
source

All Articles