首页 新闻 会员 周边

C#: 如何从 Refit 的注解(annotation) 中获取请求路径

0
悬赏园豆:50 [已解决问题] 解决于 2023-01-30 12:26

Refit 是一个 REST 库 ,可以根据 annotation 自动生成 HttpClient 请求代码 https://github.com/reactiveui/refit

想从 annotation 中获取请求路径,以便在测试代码中 mock 时重用这个路径,减少重复代码

比如下面的 annotation,想获取 v2/blogposts/public/ids,请问如何实现?最好借助 refit 已有的实现

public interface IBlogPostClient
{
    [Post("v2/blogposts/public/ids")]
    Task<int[]> GetPublicPostIds(int[] postIds);
}
问题补充:

就这样一个路径在代码中要写3遍
1、后端 web api 路由中
2、api 客户端 HttpClient 中
3、测试代码的 mock 中

dudu的主页 dudu | 高人七级 | 园豆:30948
提问于:2023-01-29 10:35
< >
分享
最佳答案
0

参考 Refit 的源码,通过 RestMethodInfo 实现了

var handler = new Mock<HttpMessageHandler>();
var httpClient = handler.CreateClient();
httpClient.BaseAddress = new Uri("http://blog_api");

var apiClientType = typeof(IBlogPostClient);
var restMethod = new RestMethodInfo(
    apiClientType,
    apiClientType.GetMethods().First(m => m.Name == nameof(IBlogPostClient.GetPublicPostIds)));

handler.SetupRequest(HttpMethod.Post, new Uri(httpClient.BaseAddress, restMethod.RelativePath))
    .ReturnsJsonResponse(publicPostIds);
dudu | 高人七级 |园豆:30948 | 2023-01-30 12:25

今天发现原来的 RestMethodInfo 被改成了 RestMethodInfoInternal,无法直接调用了,详见 https://github.com/reactiveui/refit/pull/1496

dudu | 园豆:30948 (高人七级) | 2023-08-27 10:11

改为下面更简单的实现

var apiClientType = typeof(IBlogPostClient);
var methodName = nameof(IBlogPostClient.GetPublicPostIds);
var hma = apiClientType.GetMethods().First(m => m.Name == methodName)
    .GetCustomAttributes(true)
    .OfType<HttpMethodAttribute>()
    .First();

var requestUri = new Uri(_baseAddress, hma.Path);
_mockHandler.SetupRequest(HttpMethod.Post, requestUri)
    .ReturnsJsonResponse(publicPostIds);
dudu | 园豆:30948 (高人七级) | 2023-08-27 10:21
其他回答(1)
0

1、后端 web api 路由中 必须的
2、api 客户端 HttpClient 中 refit不是有resetclient么, 用它自己的, 不直接用httpclient就可以了呀
3、测试代码的 mock 中 简单的写个扩展方法?, 大概看看 RequestBuilder.For..... 之类的方法出来的东西有没有能用的?

收获园豆:50
czd890 | 园豆:14412 (专家六级) | 2023-01-29 12:37

2、[Post("v2/blogposts/public/ids")] 就是为 refit 而写,这就是第2遍
3、mock 中的第3次可以看 https://q.cnblogs.com/q/142495/

支持(0) 反对(0) dudu | 园豆:30948 (高人七级) | 2023-01-29 13:49
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册