【问题标题】:Refit Net core AddRefitClient Read Response HeaderRefit Net core AddRefitClient 读取响应头
【发布时间】:2020-03-27 06:19:15
【问题描述】:

对于使用 Refit 处理 REST API 的 WPF .net core 3.1 应用程序,我需要以下代码的帮助。我正在尝试从响应标头中获取 AuthToken 的值。但我找不到拥有 AuthorizationHeaderValueGetter 值的属性。

我确实看到了一些与此问题相关的错误 - https://github.com/reactiveui/refit/issues/689。据称已在 .net core 3.1 版本中修复。但我还没有能够检索到响应头。

App.xaml.cs

private void ConfigureServices(IConfiguration configuration, IServiceCollection services)
        {
            services.AddRefitClient<IService>(new RefitSettings()
            {
                AuthorizationHeaderValueGetter = () => Task.FromResult("AuthToken")
            })
            .ConfigureHttpClient(c => c.BaseAddress = new 
             Uri(Configuration.GetSection("MyConfig:GatewayService").Value));
        }

IService.cs 接口 IService 定义如下:

[Headers("Content-Type: application/json")]
    public interface IService
    {
        [Post("/v1/Authtoken/")]
        public Task<string> Authenticate([Body] Authenticate payload);
    }

我在我的 ViewModel (WPF) 中注入 IService 并尝试获取应该设置的“AuthToken”标头的值。

视图模型

    public class SomeViewModel: ISomeViewModel
    {
        public SomeViewModel(IService service)
        {
            this.Service = service;
        }

        public async Task<Tuple<bool, string>> Somemethod()
        {
            var authResponse = await Service.Authenticate(authPayload);

            .......
        }

    }

【问题讨论】:

    标签: c# wpf .net-core refit httpclientfactory


    【解决方案1】:

    我设法获得了响应标头。服务的返回类型必须更改为 System.Net.Http.HttpResponseMessage。

    
    [Headers("Content-Type: application/json")]
        public interface IService
        {
            [Post("/v1/Authtoken/")]
            public Task<HttpResponseMessage> Authenticate([Body] Authenticate payload);
        }
    

    创建了一个扩展方法,用于查找响应标头以获取“AuthToken”值。

    public static class RefitExtensions
        {
            public static async Task<string>GetAuthToken(this Task<HttpResponseMessage> task)
            {
                var response = await task.ConfigureAwait(false);
                string authToken = response.Headers.GetValues("AuthToken").FirstOrDefault();
                return await Task.FromResult(authToken);
            }
        }
    

    在视图模型中,我通过以下语句得到了 authtoken 值。

    var authToken = await Service.Authenticate(authPayload).GetAuthToken();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 2021-07-28
      • 2011-01-23
      相关资源
      最近更新 更多