Servizio WCF per la ricezione di immagini
-
01-07-2019 - |
Domanda
Qual è il modo migliore per creare un servizio web per accettare un'immagine. L'immagine potrebbe essere piuttosto grande e non voglio modificare la dimensione di ricezione predefinita per l'applicazione Web. Ne ho scritto uno che accetta un'immagine binaria ma ritengo che ci debba essere un'alternativa migliore.
Soluzione
Dove si trova questa immagine "live?" È accessibile nel file system locale o sul Web? In tal caso, suggerirei che il tuo WebService accetti un URI (può essere un URL o un file locale) e lo apra come Stream, quindi usi uno StreamReader per leggere il suo contenuto.
Esempio (ma racchiudi le eccezioni in FaultExceptions e aggiungi FaultContractAttributes):
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
[OperationContract]
public void FetchImage(Uri url)
{
// Validate url
if (url == null)
{
throw new ArgumentNullException(url);
}
// If the service doesn't know how to resolve relative URI paths
/*if (!uri.IsAbsoluteUri)
{
throw new ArgumentException("Must be absolute.", url);
}*/
// Download and load the image
Image image = new Func<Bitmap>(() =>
{
try
{
using (WebClient downloader = new WebClient())
{
return new Bitmap(downloader.OpenRead(url));
}
}
catch (ArgumentException exception)
{
throw new ResourceNotImageException(url, exception);
}
catch (WebException exception)
{
throw new ImageDownloadFailedException(url, exception);
}
// IOException and SocketException are not wrapped by WebException :(
catch (IOException exception)
{
throw new ImageDownloadFailedException(url, exception);
}
catch (SocketException exception)
{
throw new ImageDownloadFailedException(url, exception);
}
})();
// Do something with image
}
Altri suggerimenti
Non riesci a caricare l'immagine sul server usando FTP, quando hai finito il server (e quindi il servizio WCF) può accedervi facilmente? In questo modo non è necessario pensare con le impostazioni relative alle dimensioni di ricezione, ecc.
Almeno, è così che l'ho fatto.