WireMock-Net / WireMock.Net

WireMock.Net is a flexible product for stubbing and mocking web HTTP responses using advanced request matching and response templating. Based on the functionality from http://WireMock.org, but extended with more functionality.
Apache License 2.0
1.39k stars 207 forks source link

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

Closed eetawil closed 7 months ago

eetawil commented 7 months ago

I tired on SO: https://stackoverflow.com/questions/77989392/wiremock-net-c-how-to-get-a-pdf-from-a-request-body-form-data

I'm also posting it here to get better reach...

=> 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)

image

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
}
StefH commented 7 months ago

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

eetawil commented 7 months ago

Thank you very much for your input and directions!