如何在.NET的Refit中通过Command传递路径参数
如何通过Refit命令类传递路径参数?
你可以借助Refit提供的[Path]特性实现需求,具体操作如下:
- 修改命令类,将原
[Query]特性替换为[Path],保证AliasAs的名称与路径占位符一致:
public sealed class GetStudentRecordCommand { public GetStudentRecordCommand(string id) { Id = id; } [Path] [AliasAs("id")] public string Id { get; private set; } = string.Empty; }
- 调整Refit接口的
[Get]特性路径,添加对应的{id}占位符:
public interface IRefitInterface { [Get("/v1/report/student-statement/{id}")] Task<GetStudentRecordResponse> GetStudentsRecordsAsync( GetStudentRecordCommand command, CancellationToken cancellationToken = default); }
原理说明:[Path]是Refit专门用于标记类属性作为URL路径参数的特性,只要属性的AliasAs值与路径中的占位符名称匹配,Refit就会自动将Command实例中对应的属性值填充到路径的对应位置,无需在方法参数中单独声明路径参数。
内容的提问来源于stack exchange,提问作者Hakuna
相关产品推荐
相关产品推荐

