我需要有关 WPF .net core 3.1 应用程序的以下代码的帮助,该应用程序使用 Refit 来处理 REST API。我正在尝试从响应 header 获取 AuthToken 的值。但我找不到保存 AuthorizationHeaderValueGetter 值的属性。
我确实看到了一些与此问题相关的错误 - https://github.com/reactiveui/refit/issues/689 。据称该问题已在.net core 3.1版本中修复。但我还无法检索响应 header 。
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 接口(interface)IService定义如下:
[Headers("Content-Type: application/json")]
public interface IService
{
[Post("/v1/Authtoken/")]
public Task<string> Authenticate([Body] Authenticate payload);
}
我正在 ViewModel (WPF) 中注入(inject) IService 并尝试获取应已设置的“AuthToken” header 的值。
View 模型
public class SomeViewModel: ISomeViewModel
{
public SomeViewModel(IService service)
{
this.Service = service;
}
public async Task<Tuple<bool, string>> Somemethod()
{
var authResponse = await Service.Authenticate(authPayload);
.......
}
}
最佳答案
我设法获取响应 header 。服务的返回类型必须更改为 System.Net.Http.HttpResponseMessage。
[Headers("Content-Type: application/json")]
public interface IService
{
[Post("/v1/Authtoken/")]
public Task<HttpResponseMessage> Authenticate([Body] Authenticate payload);
}
创建了一个扩展方法,用于查找响应 header 以获取“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);
}
}
在 View 模型中,我通过以下语句获取了 authtoken 值。
var authToken = await Service.Authenticate(authPayload).GetAuthToken();
关于c# - Refit Net core AddRefitClient 读取响应头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60880873/