Home > Blockchain >  Reuse one web response in .net and rest for many operations
Reuse one web response in .net and rest for many operations

Time:11-03

I have a question.

I have a simple service that do requests and streams back response to file and it looks like:

public async ValueTask GetWaetherByLocation(string place)
{
    try
    {
        const string locationEndpoint = "https://localhost/api/place/?query=";

        var fullEndpoint = $"{locationEndpoint}{place}";
        HttpWebRequest request = WebRequest.CreateHttp(fullEndpoint);
        WebResponse response = await request.GetResponseAsync();

        ContentDispositionHeaderValue contentDisposition;

        var fileName = ContentDispositionHeaderValue.TryParse(response.Headers["Content-Disposition"], out contentDisposition)
            ? contentDisposition.FileName
            : "place.dat";

        var filePath = Path.Combine(assemblyPathInfo, fileName);

        using var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
        await response.GetResponseStream().CopyToAsync(stream);
    }
    catch(Exception ex)
    {
        logger.Error(ex);
    }
}

My question is can I reuse stream to cast reponse to some model without the need to send request once more or opening file data is beeing streamed to?

CodePudding user response:

Why not use response caching middleware?

public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCaching();
    services.AddRazorPages();
}

By query key would help you:

var responseCachingFeature = context.HttpContext.Features.Get<IResponseCachingFeature>();

if (responseCachingFeature != null)
{
    responseCachingFeature.VaryByQueryKeys = new[] { "MyKey" };
}
  • Related