如何在 ASP.NET Core 中缓存请求?

我正在寻找如何在 ASP.NET Core 2.x 中缓存请求?


我有 API 代理,它总是使用相同的请求返回不同的响应(使用 AI 的同义词组合,因此这就是我不寻找缓存响应的原因)。


我想缓存请求,因为它总是相同的(总是相同的基本身份验证和参数来戳我正在代理的其他 API)。


由于请求使用文件input.xml作为参数,我想知道在哪里也可以缓存该文件


我的控制器:


[Route("api/v1/[controller]")]

public class CompositionController : Controller

{

    [HttpGet]

    public async Task<string> Get(string transformation = "xml")

    {

        var httpClient = new HttpClient();


        const string authScheme = @"Basic";

        const string name = @"myUserName";

        const string password = @"myPassword";

        var authBytes = Encoding.ASCII.GetBytes($@"{name}:{password}");

        var auth64BaseString = Convert.ToBase64String(authBytes);

        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authScheme, auth64BaseString);


        const string fileName = @"input.xml";

        var inputBytes = File.ReadAllBytes(fileName);

        var byteArrayContent = new ByteArrayContent(inputBytes);

        const string formDataKey = @"""file""";

        const string formDataValue = @"""input.xml""";

        var multipartFormDataContent = new MultipartFormDataContent()

        {

            { byteArrayContent, formDataKey, formDataValue }

        };


        const string url = @"http://baseurl:port/my/resource/is/there.do?transformation=" + transformation;

        var response = await httpClient.PostAsync(url, multipartFormDataContent);

        return await response.Content.ReadAsStringAsync();

    }

}


萧十郎
浏览 194回答 1
1回答

温温酱

您真的不应该在HttpClient每次调用端点时都构建一个。这就是我会做的://create a service that caches HttpClient based on urlpublic interface IHttpClientService{&nbsp; &nbsp; IHttpClient GetClient(string baseHref);&nbsp; &nbsp; void AddClient(HttpClient client, string baseHref);}//implement your interfacepublic class HttpClientService : IHttpClientService{&nbsp; &nbsp; private readonly ConcurrentDictionary<string, IHttpClient> _httpClients;&nbsp; &nbsp; public HttpClientService()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _httpClients = new ConcurrentDictionary<string, IHttpClient>();&nbsp; &nbsp; }&nbsp; &nbsp; public void AddClient(HttpClient client, string baseHref)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _httpClients.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .AddOrUpdate(baseHref, client, (key, existingHttpClient) => existingHttpClient);&nbsp; &nbsp; }&nbsp; &nbsp; public IHttpClient GetClient(string baseHref)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (_httpClients.TryGetValue(baseHref, out var client))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return client;&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }}//register as singleton Startup.csservices.AddSingleton<IHttpClientService, HttpClientService>();//inject into Controller[HttpGet]public async Task<string> Get(string transformation = "xml"){&nbsp; &nbsp; const string url = @"http://baseurl:port/my/resource/is/there.do?transformation=" + transformation;&nbsp; &nbsp; var httpClient = _httpService.GetClient(url);&nbsp; &nbsp; if(httpClient == null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; httpClient = new HttpClient(url);&nbsp; &nbsp; &nbsp; &nbsp; const string authScheme = @"Basic";&nbsp; &nbsp; &nbsp; &nbsp; const string name = @"myUserName";&nbsp; &nbsp; &nbsp; &nbsp; const string password = @"myPassword";&nbsp; &nbsp; &nbsp; &nbsp; var authBytes = Encoding.ASCII.GetBytes($@"{name}:{password}");&nbsp; &nbsp; &nbsp; &nbsp; var auth64BaseString = Convert.ToBase64String(authBytes);&nbsp; &nbsp; &nbsp; &nbsp; httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authScheme, auth64BaseString);&nbsp; &nbsp; &nbsp; &nbsp; const string fileName = @"input.xml";&nbsp; &nbsp; &nbsp; &nbsp; var inputBytes = File.ReadAllBytes(fileName);&nbsp; &nbsp; &nbsp; &nbsp; var byteArrayContent = new ByteArrayContent(inputBytes);&nbsp; &nbsp; &nbsp; &nbsp; const string formDataKey = @"""file""";&nbsp; &nbsp; &nbsp; &nbsp; const string formDataValue = @"""input.xml""";&nbsp; &nbsp; &nbsp; &nbsp; var multipartFormDataContent = new MultipartFormDataContent()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { byteArrayContent, formDataKey, formDataValue }&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; _httpClient.AddClient(httpClient, url);&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; //You can cache your MultipartFormDataContent in MemoryCache or same cache as HttpClient&nbsp; &nbsp; &nbsp;//Get MultipartFormDataContent from cache and&nbsp; &nbsp; }&nbsp; &nbsp; var response = await httpClient.PostAsync(url, multipartFormDataContent);&nbsp; &nbsp; return await response.Content.ReadAsStringAsync();}
打开App,查看更多内容
随时随地看视频慕课网APP