You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET的Refit中通过Command传递路径参数

如何通过Refit命令类传递路径参数?

你可以借助Refit提供的[Path]特性实现需求,具体操作如下:

  1. 修改命令类,将原[Query]特性替换为[Path],保证AliasAs的名称与路径占位符一致:
public sealed class GetStudentRecordCommand
{
    public GetStudentRecordCommand(string id)
    {
        Id = id;
    }
    
    [Path]
    [AliasAs("id")]
    public string Id { get; private set; } = string.Empty;
}
  1. 调整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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 07:15:00