Download/Upload File Using WCF REST Services With Windows Authentication

I have seen many articles for downloading and uploading files and in nearly everyone, the old way of copying the stream data was used. In the .Net Framework 4.0 there is a new method, Stream.CopyTo that makes it really easy for copying the stream data. Also, I have not seen any article that uploads/downloads a file using a Windows authenticated WCF REST service hosted on IIS. So, I thought of writing one with all that.
 
In this article share how to easily download and upload a file using a Windows Authenticated WCF service hosted in IIS. The client will be a C# windows client that will send the request for downloading and uploading the file.
 
The source code is attached with the article.
 

WCF REST Service

 
The first step is to create a WCF REST service that will be used for downloading and uploading the file. I prefer to keep all my services in a separate WCF project. This project is then hosted in the IIS.
  1. Add a new Blank solution by the name of “FileHandling”.
  2. Add a new WCF Service Application and give it the name FileHandling.WCFHost.


     
  3. Right-click the FileHandling.WCFHost project in Visual Studio and go to the properties. Under the Web tab click on “Use local IIS WebServer” and under the Project URL, write “http://localhost/FileHandling.WCFHost” and click on the button “Create Virtual Directory”. This will create a Virtual Directory for FileHandling.WCFHost in IIS.


     
  4. Go to IIS and check if the Virtual Directory is created.


     
  5. Ensure that the App Pool associated to the account is of .Net Framework 4.0. Also, the App Pool should be running under the identity of the user that has Read/write rights on any folder of the server. WCF uses this identity for doing all its network operations. In this case I run the App Pool under my account, but it is not mandatory, you can choose a different account having permissions as well.



     
  6. Ensure that for the FileHandling.WCFHost, only Windows Authentication is enabled.



    With the preceding steps the IIS configuration is complete. Now it's time to add the service.
     
  7. Add a new WCFService in the FileHost.WCFHost project in VisualStudio and give it the name FileManagerService.


     
  8. In the IFileManagerService add the following methods.
    1. using System.IO;  
    2. using System.ServiceModel;  
    3. using System.ServiceModel.Web;  
    4.   
    5. namespace FileHandling.WCFHost  
    6. {  
    7.     [ServiceContract]  
    8.     public interface IFileManagerService  
    9.     {  
    10.   
    11.         [OperationContract]  
    12.         [WebGet(UriTemplate = "RetrieveFile?Path={path}")]  
    13.         Stream RetrieveFile(string path);  
    14.   
    15.         [OperationContract]  
    16.         [WebInvoke(UriTemplate = "UploadFile?Path={path}")]  
    17.         void UploadFile(string path, Stream stream);  
    18.   
    19.     }  

  9. In the FileManagerService.svc.cs add the following code:
    1. using System;  
    2. using System.IO;  
    3. using System.ServiceModel.Web;  
    4.   
    5. namespace FileHandling.WCFHost  
    6. {  
    7.     public class FileManagerService : IFileManagerService  
    8.     {  
    9.         public Stream RetrieveFile(string path)  
    10.         {  
    11.             if(WebOperationContext.Current == nullthrow new Exception("WebOperationContext not set");  
    12.   
    13.             // As the current service is being used by a windows client, there is no browser interactivity.  
    14.             // In case you are using the code Web, please use the appropriate content type.  
    15.             var fileName = Path.GetFileName(path);  
    16.             WebOperationContext.Current.OutgoingResponse.ContentType= "application/octet-stream";  
    17.             WebOperationContext.Current.OutgoingResponse.Headers.Add("content-disposition""inline; filename=" + fileName);  
    18.   
    19.             return File.OpenRead(path);  
    20.         }  
    21.   
    22.         public void UploadFile(string path, Stream stream)  
    23.         {  
    24.             CreateDirectoryIfNotExists(path);  
    25.             using (var file = File.Create(path))  
    26.             {  
    27.                 stream.CopyTo(file);  
    28.             }  
    29.         }  
    30.   
    31.         private void CreateDirectoryIfNotExists(string filePath)  
    32.         {  
    33.             var directory = new FileInfo(filePath).Directory;  
    34.             if (directory == nullthrow new Exception("Directory could not be determined for the filePath");  
    35.   
    36.             Directory.CreateDirectory(directory.FullName);  
    37.         }  
    38.     }  

    The RetrieveFile method is used for downloading the file. The method takes the parameter “path”, that is the location of the file for downloading from the WCF server. The method itself is pretty simple, it sets the ContentType and filename in the Response Header and then sends the FileStream back. Do not worry about how this FileStream will be disposed. WCF automatically takes care of it and at the end of the method disposes of it.

    The UploadFile is also pretty simple. It takes the following two parameters:

    • path: Path where the uploaded file should be saved
    • stream: Stream represents the Uploaded file.

    The method creates the Directory if it does not already exist and then creates the file in the location specified by “path”. For copying the uploaded file in the “path” location, Stream.CopyTo has been used.
     
  10. It's time to add the configuration settings for the service. In the Web.Config add the following configuration.
    1.   <system.serviceModel>  
    2.     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />  
    3.     <bindings>  
    4.       <webHttpBinding>  
    5.         <binding name="ServiceWebBindingName" transferMode="Streamed" maxReceivedMessageSize="2147483647" >  
    6.           <readerQuotas  maxArrayLength="2147483647" maxStringContentLength="2147483647" />  
    7.           <security mode="TransportCredentialOnly">  
    8.             <transport clientCredentialType="Windows"></transport>  
    9.           </security>   
    10.         </binding>  
    11.       </webHttpBinding>  
    12.     </bindings>  
    13.     <behaviors>  
    14.       <endpointBehaviors>  
    15.         <behavior name="DefaultRestServiceBehavior">  
    16.           <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="false"/>  
    17.         </behavior>  
    18.       </endpointBehaviors>  
    19.       <serviceBehaviors>  
    20.         <behavior name="">  
    21.           <serviceMetadata httpGetEnabled="true" />  
    22.           <serviceDebug includeExceptionDetailInFaults="true" />  
    23.         </behavior>  
    24.       </serviceBehaviors>  
    25.     </behaviors>  
    26.     <services>  
    27.       <service name="FileHandling.WCFHost.FileManagerService">  
    28.         <endpoint address=""  
    29.               binding="webHttpBinding"  
    30.               bindingConfiguration="ServiceWebBindingName"  
    31.               behaviorConfiguration="DefaultRestServiceBehavior"  
    32.               name="FileManagerServiceEndpoint"  
    33.               contract="FileHandling.WCFHost.IFileManagerService"/>  
    34.       </service>  
    35.     </services>  
    36.   </system.serviceModel>  
    37. </configuration> 
    Please note that the Transfermode has been set to “Streamed”. This will ensure that the file is streamed to the client. And also, notice that I have given maximum values to maxReceivedMessageSize, maxArrayLength, maxStringContentLength. This will ensure that large files can be transferred as well.
    1. <binding name="ServiceWebBindingName" transferMode="Streamed" maxReceivedMessageSize="2147483647" >  
    2. <readerQuotas  maxArrayLength="2147483647" maxStringContentLength="2147483647" />  
    3.           <security mode="TransportCredentialOnly">  
    4.             <transport clientCredentialType="Windows"></transport>  
    5.           </security>  
    6.         </binding>  
    7.       </webHttpBinding>  
    8. </bindings> 
    Also note that for Security mode has been set to TransportCredentialsOnly and the ClientCredentialType has been set to Windows.
Client
 
Now it's time to build the Client.
 
I decided to use a simple Windows client for consuming the WCF service for downloading and uploading the file. Methods for uploading and downloading are specified below.
 

File Upload using WCF

 
The UploadFileToRemoteLocation method takes the following 2 parameters:
  • filePath: specifies the local path of where the file is located.
  • destinationFilePath: specifies the path on the server (on which WCF is hosted) where file must be uploaded.
The method UploadFileToRemoteLocation copies the file specified in the filePath to the request stream. It then calls the WCF service for uploading this file and passes destinationFilePath as the path where the file should be stored on the server.
 
The service on being called receives the file and then saves it at the destinationFilePath on the server.
 
In this example, both WCFHost and the client are located on the same server but the WCFHost can be located on any other server as well. 
  1. /// <summary>    
  2. /// Uploads file to remote location    
  3. /// </summary>    
  4. private void UploadFileToRemoteLocation(string filePath, string destinationFilePath)    
  5. {    
  6.     var serviceUrl = string.Format("{0}/UploadFile?Path={1}", FileManagerServiceUrl, destinationFilePath);    
  7.     var request = (HttpWebRequest)WebRequest.Create(serviceUrl);    
  8.     request.Method = "POST";    
  9.     request.UseDefaultCredentials = true;    
  10.     request.PreAuthenticate = true;    
  11.     request.Credentials = CredentialCache.DefaultCredentials;    
  12.   
  13.     using (var requestStream = request.GetRequestStream())    
  14.     {    
  15.         using (var file = File.OpenRead(filePath))    
  16.         {    
  17.             file.CopyTo(requestStream);    
  18.         }    
  19.     }  
  20.     using (var response = request.GetResponse() as HttpWebResponse)    
  21.     {    
  22.         // Do Nothing         
  23.     }  
  24. }

File Download using WCF

 
The method DownloadFileFromRemoteLocation takes the following 2 parameters:
  • downloadFileLocation: This is the path on the server where the file is located.
  • downloadedFileSaveLocation: This is the local path where the file is saved after downloading.
The DownloadFileFromRemoteLocation method first downloads file from the service and then stores the file in the path specified in downloadedFileSaveLocation.
  1. private void DownLoadFileFromRemoteLocation(string downloadFileLocation, string downloadedFileSaveLocation) {  
  2.  string serviceUrl = string.Format("{0}/RetrieveFile?Path={1}", FileManagerServiceUrl, downloadFileLocation);  
  3.  var request = WebRequest.Create(serviceUrl);  
  4.  request.UseDefaultCredentials = true;  
  5.  request.PreAuthenticate = true;  
  6.  request.Credentials = CredentialCache.DefaultCredentials;  
  7.   
  8.  try {  
  9.   using(var response = request.GetResponse()) {  
  10.    using(var fileStream = response.GetResponseStream()) {  
  11.     if (fileStream == null) {  
  12.      MessageBox.Show("File not recieved");  
  13.      return;  
  14.     }  
  15.   
  16.     CreateDirectoryForSaveLocation(downloadedFileSaveLocation);  
  17.     SaveFile(downloadedFileSaveLocation, fileStream);  
  18.    }  
  19.   }  
  20.   
  21.   MessageBox.Show("File downloaded and copied");  
  22.   
  23.  } catch (Exception ex) {  
  24.   MessageBox.Show("File could not be downloaded or saved. Message :" + ex.Message);  
  25.  }  
  26.   
  27. }  
  28.   
  29. private static void SaveFile(string downloadedFileSaveLocation, Stream fileStream) {  
  30.  using(var file = File.Create(downloadedFileSaveLocation)) {  
  31.   fileStream.CopyTo(file);  
  32.  }  
  33. }  
  34.   
  35. private void CreateDirectoryForSaveLocation(string downloadedFileSaveLocation) {  
  36.  var fileInfo = new FileInfo(downloadedFileSaveLocation);  
  37.  if (fileInfo.DirectoryName == nullthrow new Exception("Save location directory could not be determined");  
  38.  Directory.CreateDirectory(fileInfo.DirectoryName);  
  39. }  
Please refer to the attached code if you would like to have a look at the complete working solution.
 
The following are the prerequisites for the attached code to work:
  • IIS should be installed.
  • .Net Framework 4.0 should be installed
  • Visual Studio 2010 or above.


Similar Articles