Skip to content

Instantly share code, notes, and snippets.

@kant2002
Created May 23, 2023 12:53
Show Gist options
  • Save kant2002/f322d8b1c58328a9545bf0ad72eed1c8 to your computer and use it in GitHub Desktop.
Save kant2002/f322d8b1c58328a9545bf0ad72eed1c8 to your computer and use it in GitHub Desktop.
Intercepting responses
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
internal class FromFolderDelegatingHandler : DelegatingHandler
{
private readonly string folder;
private readonly string captureFolder;
private Dictionary<string, int> endpointsIncrement = new Dictionary<string, int>();
public FromFolderDelegatingHandler(string folder, string captureFolder)
{
this.folder = folder;
this.captureFolder = captureFolder;
Directory.CreateDirectory(folder);
Directory.CreateDirectory(captureFolder);
foreach (var file in Directory.GetFiles(captureFolder))
{
File.Delete(file);
}
}
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var requestUri = request.RequestUri;
var path = requestUri!.LocalPath;
var method = request.Method;
var baseName = method + "_" + path.Substring(1).Replace("/", "_");
var fileToReturn = this.GetRequestFileName(this.folder, baseName);
var fileToCapture = this.GetRequestFileName(this.captureFolder, baseName);
if (request.Content != null)
{
var requestContent = await request.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
await File.WriteAllTextAsync(fileToCapture, requestContent, cancellationToken).ConfigureAwait(false);
}
else if (request.Method == HttpMethod.Post)
{
await File.WriteAllTextAsync(fileToCapture, string.Empty, cancellationToken).ConfigureAwait(false);
}
var content = await File.ReadAllTextAsync(fileToReturn, cancellationToken).ConfigureAwait(false);
var responseContent = new StringContent(content, Encoding.UTF8, "application/json");
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = responseContent,
};
return response;
}
private string GetRequestFileName(string folder, string baseName)
{
var basePath = Path.Combine(folder, baseName);
var increment = this.GetEndpointIncrement(basePath);
this.endpointsIncrement[basePath] = increment + 1;
if (increment != 0)
{
basePath = basePath + "_" + increment;
}
return basePath + ".json";
}
private int GetEndpointIncrement(string key)
{
int increment = 0;
this.endpointsIncrement.TryGetValue(key, out increment);
if (increment == 0)
{
return 0;
}
return increment;
}
}
var httpClient = new HttpClient(new FromFolderDelegatingHandler(responsesFolderApi, captureFolderApi)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment