如何在 Refit 的强类型对象中发布 URL 编码字典

发布于 2025-01-18 05:19:13 字数 1551 浏览 0 评论 0原文

我正在尝试复制一个编码的表单数据请求,该数据请求包含邮政字典中的字典到 recrit 但我无法进行获取(重新安装)以产生相同的编码数据。请参阅下面的比较,并注意到来自Refit的编码数据似乎已经完成了.toString()在字典上,而不是像Postman一样对其进行编码。

该功能是否内在进行重新装置,还是我必须以某种方式实现自定义编码器?似乎这是一个相当普遍的用例,所以我不确定我缺少什么。

Postman

请求和URL编码表格数据:

Body=Test&AllowContact=true&Context=postman&QuestionsAnswers%5B0%5D.Key=Question&QuestionsAnswers%5B0%5D.Value=2

[Post("/feedback")]
Task<ApiResponse<HttpResponseMessage>> PostFeedback(
    [Body(BodySerializationMethod.UrlEncoded)] PostFeedbackRequest request);

public record PostFeedbackRequest(
    string Body,
    bool AllowContact,
    string Context,
    IDictionary<string, int>? QuestionsAnswers = null);

var response = await Api.PostFeedback(
    new PostFeedbackRequest(
        "Test",
        true,
        "Refit",
        new Dictionary<string, int>
        {
          ["Question"] = 2,
        }));

Body=Test&AllowContact=True&Context=Refit&QuestionsAnswers=System.Collections.Generic.Dictionary%602%5BSystem.String%2CSystem.Int32%5D

I am trying to replicate a URL Encoded Form Data request that contains a dictionary from Postman into Refit but I cannot get it (Refit) to produce the same encoded data. See the comparisons below and notice that the encoded data from Refit has seemingly done .ToString() on the dictionary rather than encoding it the same way that Postman has.

Is this functionality built in to Refit or will I somehow have to implement a custom encoder? It seems like this would be a fairly common use-case so I'm not sure what I'm missing.

Postman

Request and Url Encoded form data:

Postman Request

Body=Test&AllowContact=true&Context=postman&QuestionsAnswers%5B0%5D.Key=Question&QuestionsAnswers%5B0%5D.Value=2

Refit

API definition:

[Post("/feedback")]
Task<ApiResponse<HttpResponseMessage>> PostFeedback(
    [Body(BodySerializationMethod.UrlEncoded)] PostFeedbackRequest request);

Request definition:

public record PostFeedbackRequest(
    string Body,
    bool AllowContact,
    string Context,
    IDictionary<string, int>? QuestionsAnswers = null);

API call:

var response = await Api.PostFeedback(
    new PostFeedbackRequest(
        "Test",
        true,
        "Refit",
        new Dictionary<string, int>
        {
          ["Question"] = 2,
        }));

Url Encoded form data:

Body=Test&AllowContact=True&Context=Refit&QuestionsAnswers=System.Collections.Generic.Dictionary%602%5BSystem.String%2CSystem.Int32%5D

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文