Search code examples
c#asp.net-mvcapirestrestsharp

Invocation of REST API in c# that is expecting File object


Our application has a WEB GUI that has an interface to accept the local file location and name. We have written a C# controller that is invoked while clicking submit button. The controller receives the file as HttpPostedFileBase. From the controller, we are trying to invoke the REST API in C# that is expecting the File object as a request however we are unable to do so. The request is expecting the file and the request parameter is of form-data type. Any help to write a C# REST API client to invoke this REST service by passing the file.

below is my model code : PoSPRegistration model

in the above code image is received in HttpPostedFileBase object.

below is controller code : controller post method

can't add image object in request.addfile method because it includes name and filepath


Solution

  • The RestRequest class in RestSharp has an overload of the AddFile method that takes a callback that is called to write data to a Stream object:

    AddFile(string name, 
            Action<Stream> writer, 
            string fileName, 
            long contentLength, 
            string contentType = null)
    

    You can use it like that to post data from a HttpPostedFileBase:

    request.AddFile("pan", 
                    stream => objmodel.doc_pan.InputStream.CopyTo(stream), 
                    objmodel.doc_pan.FileName, 
                    objmodel.doc_pan.ContentLength, 
                    objmodel.doc_pan.ContentType);