2012-09-04 39 views
5

Tôi muốn xác thực phần mở rộng tệp của tệp tải lên trong ASP.NET Web API (lưu ý: Tôi nhận ra rằng đây không phải là phương pháp xác thực đầy đủ).Cách xác thực tải lên tệp trong ASP.NET Web API

Tôi đang sử dụng MultipartFormDataStreamProvider để xử lý tệp Đã đăng. Vì Request.Content.Headers.ContentDisposition là null trước khi nhà cung cấp xử lý tệp (qua số ReadAsMultipartAsync), đâu là nơi tốt nhất để xác thực tên tệp của yêu cầu?

Trả lời

7

Bạn có thể kế thừa từ MultipartFormDataStreamProvider và ghi đè GetLocalFileName (chạy sau khi đọc nội dung vào luồng) hoặc GetStream (chạy trước khi đọc nội dung vào luồng). Trong cả hai trường hợp, bạn có quyền truy cập vào 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) 
    } 
} 
Các vấn đề liên quan