Search code examples
wiremockwiremock.net

Wiremock.net (C#) how to get a PDF from a Request body (form-data )


We are using wiremock.net (C#) and we want to extract from the request the PDF file contained in that Request. How can we do that? I'm new to wiremock and I read about response templating without success.

Can someone please help with either documentation or code sample for this?

In other words how to GET_PDF FILE_HERE_FROM_REQUEST (see code below)

enter image description here

wireMockServer
            .Given(Request.Create().WithPath("/validatePDFA").UsingPost())
            .RespondWith(Response.Create()
                .WithStatusCode(200)
                .WithHeader("Content-Type", "form-data")
                .WithBody(req => ReadFileAndGenerateJsonBody(GET_PDF FILE_HERE_FROM_REQUEST))                    
            );

 public string ReadFileAndGenerateJsonBody(...)
{
     //read text from PDF  file 
     //build jsonResponse
     return jsonResponse
}

Solution

  • Please refer to the answer by a great guy (he must be!) @stefH

    Here is the full text =>

    In your example you are posting a form which has 2 fields: a file field, which contains the PDF and a json text field.

    If you want to return a JSON response, you need to use the method (which gives you the request object and should return an anonymous object which will be serialized to JSON:

    IResponseBuilder WithBodyAsJson(Func<IRequestMessage, Task<object>> bodyFactory, Encoding? encoding = null);
    

    And the IRequestMessage contains a property BodyAsMimeMessage which is an MimeKit.MimeMessage object which contains several body parts which you can get and use if needed. Example:

    foreach (var mimePart in message.BodyParts.OfType<MimeKit.MimePart>())
    {
    // ...
    }
    

    See https://github.com/jstedfast/MimeKit for more details