为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
萧十郎 2021-11-07 19:37:13
我正在寻找如何在 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();    }}
查看完整描述

1 回答

?
温温酱

TA贡献1752条经验 获得超4个赞

您真的不应该在HttpClient每次调用端点时都构建一个。


这就是我会做的:


//create a service that caches HttpClient based on url

public interface IHttpClientService

{

    IHttpClient GetClient(string baseHref);

    void AddClient(HttpClient client, string baseHref);

}


//implement your interface

public class HttpClientService : IHttpClientService

{

    private readonly ConcurrentDictionary<string, IHttpClient> _httpClients;


    public HttpClientService()

    {

        _httpClients = new ConcurrentDictionary<string, IHttpClient>();

    }


    public void AddClient(HttpClient client, string baseHref)

    {

        _httpClients.

                .AddOrUpdate(baseHref, client, (key, existingHttpClient) => existingHttpClient);

    }


    public IHttpClient GetClient(string baseHref)

    {

        if (_httpClients.TryGetValue(baseHref, out var client))

            return client;

        return null;

    }

}


//register as singleton Startup.cs

services.AddSingleton<IHttpClientService, HttpClientService>();


//inject into Controller


[HttpGet]

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

{


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



    var httpClient = _httpService.GetClient(url);

    if(httpClient == null)

    {

        httpClient = new HttpClient(url);


        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 }

        };


        _httpClient.AddClient(httpClient, url);


    }

    else

    {

      //You can cache your MultipartFormDataContent in MemoryCache or same cache as HttpClient

     //Get MultipartFormDataContent from cache and

    }


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

    return await response.Content.ReadAsStringAsync();

}


查看完整回答
反对 回复 2021-11-07
  • 1 回答
  • 0 关注
  • 193 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信