2012-10-15 19 views
8

il modello:è possibile avere modelbinding in asp.net webapi con file caricato?

public class UploadFileModel 
{ 
    public int Id { get; set; } 
    public string FileName { get; set; } 
    public HttpPostedFileBase File { get; set; } 
} 

il controller:

public void Post(UploadFileModel model) 
{ 
    // never arrives... 
} 

sto ottenendo un errore

"No MediaTypeFormatter è a disposizione per leggere un oggetto di tipo 'UploadFileModel' dai contenuti con tipo di supporto "multipart/form-data". "

C'è comunque intorno a questo?

risposta

6

Non è facilmente possibile. Il binding del modello in Web API è fondamentalmente diverso rispetto a MVC e dovresti scrivere un MediaTypeFormatter che legge il flusso di file nel tuo modello e inoltre associa primitive che possono essere considerevolmente impegnative.

La soluzione più semplice è quella di afferrare il flusso di file fuori la richiesta utilizzando un certo tipo di MultipartStreamProvider e gli altri parametri utilizzando FormData nome valore di raccolta fuori quel provider

Esempio - http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2:

public async Task<HttpResponseMessage> PostFormData() 
{ 
    if (!Request.Content.IsMimeMultipartContent()) 
    { 
     throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
    } 

    string root = HttpContext.Current.Server.MapPath("~/App_Data"); 
    var provider = new MultipartFormDataStreamProvider(root); 

    try 
    { 
     await Request.Content.ReadAsMultipartAsync(provider); 

     // Show all the key-value pairs. 
     foreach (var key in provider.FormData.AllKeys) 
     { 
      foreach (var val in provider.FormData.GetValues(key)) 
      { 
       Trace.WriteLine(string.Format("{0}: {1}", key, val)); 
      } 
     } 

     return Request.CreateResponse(HttpStatusCode.OK); 
    } 
    catch (System.Exception e) 
    { 
     return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); 
    } 
} 
+0

ok, grazie! e anche grazie per il tuo sito – user10479

Problemi correlati