Click here to Skip to main content
15,880,796 members
Articles / Programming Languages / C#

Passing Multiple File Using Rest Sharp To Service Stack Windows Service

Rate me:
Please Sign up or sign in to vote.
1.80/5 (2 votes)
8 Apr 2018CPOL2 min read 12.6K   213   5  
Passing Multiple File Using Rest Sharp To Service Stack Windows Service

Introduction

Recently, I was working on the functionality to pass multiples files using REST API to Service Stack Windows Service. Didn't find much helpful information on how to achieve the same, so thought of sharing my experience on how I achieved the functionality.

I created two applications, Service (Service Stack Windows Service Empty) and Client (Console Application).

Client will pass multiple files and other parameters to Service Stack Window Service using REST API. Then, Service will read those files and will save them at some location.

Creating a Service - Service Stack Windows Service Empty

Step 1

Open Visual Studio -> Tools -> Extensions and Update.. And Install ServiceStackVS.

Image 1

Step 2

Create a New Project, let's name it - (ServiceStackWindowsService)

Image 2

This will automatically create all Projects required for ServiceStack Windows Service. Below are the projects that will get created:

Image 3

Step 3

Open ServiceStackWindowsService.ServiceModel and create a StreamFiles Class (DTO) implements IRequiresRequestStream.

Add RouteAttribute over StreamFiles which will be used while calling from Client.

C#
using ServiceStack;
using ServiceStack.Web;

namespace ServiceStackWindowsService.ServiceModel
{
    [Route("/stream","Post")]
    public class StreamFiles : IRequiresRequestStream
    {
        public System.IO.Stream RequestStream { get; set; }
        public string OtherData1 { get; set; }
        public string OtherData2 { get; set; }
    }
}

Step 4

Open ServiceStackWindowsService.ServiceInterface and Add Post method in MyServices.cs.

The below code will read the files from base.Request.Files sent by Client and save it in C:\Temp location.

Note: Please create the folder if you want to execute the attached code or give some other location on your machine before running the service.

C#
using ServiceStack;
using ServiceStack.Web;
using ServiceStackWindowsService.ServiceModel;
using System.IO;

namespace ServiceStackWindowsService.ServiceInterface
{
    public class MyServices : Service
    {
        public object Any(Hello request)
        {
            return new HelloResponse { Result = $"Hello, {request.Name}!" };
        }

        public object Post(StreamFiles streamFiles)
        {
            string resultFile = "";
            IHttpFile[] files = base.Request.Files;
            for (int i = 0; i < files.Length; i++)
            {
                resultFile = Path.Combine(@"C:\Temp", files[i].FileName);

                if (File.Exists(resultFile))
                {
                    File.Delete(resultFile);
                }

                using (FileStream file = File.Create(resultFile))
                {
                    files[i].InputStream.Seek(0, SeekOrigin.Begin);
                    files[i].InputStream.CopyTo(file);
                }
            } 
            
            return new HttpResult(System.Net.HttpStatusCode.OK);
        }
    }
}

Step 5

Run the application. The Service will be exposed at http://localhost:8088.

Image 4

Now our Service Stack Windows Service is ready. Let's jump to consuming Service in Client.

Creating a Client - Windows Console Application

Step 1

Open a new Instance of Visual Studio and create a Windows -> Console Application.

Image 5

Step 2

Install REST Sharp Nuget Package (https://www.nuget.org/packages/RestSharp) on Windows Console Application:

PM > Install-Package RestSharp -Version 106.2.1

Step 3

Call Service Stack Windows Service in Console application using REST client. To do it, write below in Client:

C#
using RestSharp;
using System.IO;

namespace ServiceStackClient
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create Rest Client
            RestClient client = new RestClient("http://localhost:8088");

            var restRequest = new RestRequest("/stream", Method.POST);

            restRequest.AddParameter("OtherData1","Value1");
            restRequest.AddParameter("OtherData2", "Value2");

            restRequest.AddHeader("Content-Length", int.MaxValue.ToString());

            //Convert File to Byte Array
            byte[] byteArray1 = File.ReadAllBytes(@"../../Files/custom.js");
            byte[] byteArray2 = File.ReadAllBytes(@"../../Files/Desert.jpg");

            //Add Files in Rest Request
            restRequest.AddFile("custom", byteArray1, "custom.js", "application/javascript");
            restRequest.AddFile("Desert", byteArray2, "Desert.jpg", "image/jpeg");

            IRestResponse response = client.Execute(restRequest);
            
            var content = response.Content;
        }
    }
}

Step 4

Run the Client Application.

Below will be the output in C:\Temp:

Image 6

That's it! We have achieved the functionality !!!

Sample code is attached in the article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --