2016-03-16 19 views
10

Fondamentalmente sto cercando di caricare un'immagine con un enum utilizzando Web API 2.Come caricare il file e il modello usando l'API Web?

ecco la firma di controllo:

[HttpPost] 
public UploadResponseVm Upload([FromBody]ResImageType type) 
{ 

Il fatto è che ogni volta che provo ad inviare un modulo multistrato (con un file e un tipo) ottengo un errore 415:

{"Message":"The request entity's media type 'multipart/form-data' is not supported for this resource.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'ResImageType' from content with media type 'multipart/form-data'.","ExceptionType":"System.Net.Http.UnsupportedMediaTypeException","StackTrace":" at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable 1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable 1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"}

ho anche aggiunto quanto segue alla mia classe startup.cs:

config.Formatters.Insert(0, new System.Net.Http.Formatting.JsonMediaTypeFormatter()); 

Come posso caricare un modello insieme a un file utilizzando un controller web api?

risposta

0

Non esiste un formattatore che possa gestire/riguardare l'oggetto . Una volta ho risolto un problema simile senza un formattatore utilizzando un metodo senza parametri e ho elaborato i dati all'interno del metodo. Ad esempio:

public async Task<HttpResponseMessage> PostFormData() 
    { 
     if (!Request.Content.IsMimeMultipartContent("form-data")) 
     { 
      return Request.CreateResponse(HttpStatusCode.BadRequest); 
     } 

      string upDir= "PathOfDirectory"; 

      MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(upDir);     
      MultipartFileStreamProvider multipartFileStreamProvider = await Request.Content.ReadAsMultipartAsync(streamProvider); 

      // Loop through files. 
      foreach (MultipartFileData file in streamProvider.FileData) 
      { 
       // Save filepaths to DB or do something else 
      } 
      return Request.CreateResponse(HttpStatusCode.OK); 
    } 

soluzione simili da MS Docs

Un'altra possibilità è quella di creare una classe DTO-like che viene utilizzato per trasferire l'oggetto e utilizzare un formattatore, ad esempio MultipartDataMediaFormatter sembra legittimo (non hanno provato).