简体   繁体   English

改装 - 如何拥有可选的动态标题

[英]Refit - How to have OPTIONAL dynamic headers

I am using Refit and would like to set OPTIONAL dynamic headers for some methods.我正在使用 Refit 并希望为某些方法设置 OPTIONAL 动态标头。 For example if the user is logged in, I want to have header "UserId" and "AuthenticationToken", otherwise do NOT set the headers例如,如果用户登录,我想要标题“UserId”和“AuthenticationToken”,否则不要设置标题

[Post("/search")]
Task<SearchResponse> Search([Body]SearchRequest request, [Header("UserId")] string userId,[Header("AuthorizationToken")] string token);

Not sure if I pass null value to userId and token, the two headers will have null value or just be skipped (not included in the header)?不确定我是否将 null 值传递给 userId 和 token,这两个标头将具有 null 值还是被跳过(不包含在标头中)?

Thanks.谢谢。

Using refit you can implement DelegatingHandler and then register that to do whatever you need to the http request before it is sent on.使用改装,您可以实现 DelegatingHandler 然后注册它以在发送之前对 http 请求执行任何您需要的操作。 Here is adding an origin header to each request.这是为每个请求添加一个原始标头。 Refit interface does not need to worry about it. Refit 接口不需要担心。

public class AddOriginHeaderToRequest : DelegatingHandler
    {
        private const string ServiceNameSettingLocation = "AppConfig:Logging:ServiceName";

        private readonly IHttpContextAccessor httpContextAccessor;

        private readonly IConfiguration configuration;

        public AddOriginHeaderToRequest(IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
        {
            this.httpContextAccessor = httpContextAccessor;
            this.configuration = configuration;
        }

        protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            var origin = this.configuration[AddOriginHeaderToRequest.SomethingThatShouldBeDefined];

            if (!(request.Headers.Contains("origin") || request.Headers.Contains("Origin")) && origin != null)
            {
                request.Headers.Add("origin", origin);
            }

            return await base.SendAsync(request, cancellationToken);
        }
    }

Then register it like this:然后像这样注册它:

services.AddTransient<AddOriginHeaderToRequest>();

Then the refit client can be registered like this (this is a redacted version of one of our nuget packages so will hopefully give an idea of how it works):然后可以像这样注册改装客户端(这是我们的一个 nuget 软件包的编辑版本,因此希望能够了解它是如何工作的):

public static IHttpClientBuilder AddHttpClientWithDefaultHandlers(
            this IServiceCollection services,
            string name,
            Action<HttpClient> configureClient)
        {
            return services.AddHttpClient(name, configureClient)
                .AddHttpMessageHandler<AddOriginHeaderToRequest>();
        }

Then in our service we register our refit handler like this:然后在我们的服务中,我们像这样注册我们的改装处理程序:

services.AddHttpClientWithRefitAndDefaultHandlers<ImyHttpClient>(
                "myHttpClient",
                c =>
                {
                    c.BaseAddress = new Uri(appSettings.Value.AppConfig.SomeUrl);
                });

This can be simplified but we have a number of different handlers that massage our http requests in a standard way.这可以简化,但我们有许多不同的处理程序以标准方式处理我们的 http 请求。

I hope that gives you a pointer to how it could work.我希望这能给你一个关于它如何工作的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM