Tom
Tom

Reputation: 135

Dump a json response to a file

how do you dump a json response to a file?

Basically I can’t hit the api directly, so for debugging reasons I would like to dump the response to a file on the hosting server then download the file, where I can work with it.

Upvotes: 1

Views: 2502

Answers (2)

Felix D.
Felix D.

Reputation: 5123

To simply dump to a file do this:

[... //Do your WebRequest...]

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    //Here you got the JSON as string:
    var result = streamReader.ReadToEnd()

    // Write the text to a new file named "Response.json".
    File.WriteAllText(@"C:\temp\Response.json", result );

    return result;
}

Note this will overwrite your file everytime your getting the response. In order to prevent that you could add a timestamp to the fileName.

//This will (atleast every second) create a unique filename
string filePath = $@"C:\temp\Response{DateTime.Now.ToString("ddMMyyyyHHmmss")}"; 

Edit:

To ensure your files are transfered to your bin\Debug folder you could use the following:

string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Response{DateTime.Now.ToString("ddMMyyyyHHmmss")}");

Upvotes: 2

Aleksey L.
Aleksey L.

Reputation: 37996

You can define custom DelegatingHandler:

public class LogResponseHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        var responseString = await response.Content.ReadAsStringAsync();

        //log response string to file

        return response;
    }
}

Register it in HttpConfiguration

config.MessageHandlers.Add(new LogResponseHandler());

Upvotes: 2

Related Questions