0

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
Steve Wilford
  • 8,894
  • 5
  • 42
  • 66
  • Not really an answer but just pointing out it is not the same thing - in Postman you do not have a dictionary. I guess it would also work if in Refit you'd use a `Dictionary QuestionsAnswers` instead of the custom model. The dictionary would then be populated with the exact same values as in Postman so Body = Test, etc.. QuestionAnswers[0].Key = Question ... – Cristian Teodorov Mar 30 '22 at 15:27
  • Changing to Dictionary resulted in essentially the same form data: Body=Test&AllowContact=True&Context=Refit&QuestionsAnswers=System.Collections.Generic.Dictionary%602%5BSystem.String%2CSystem.Object%5D – Steve Wilford Mar 30 '22 at 19:46
  • Sorry, I wanted to say it would probably work if you used a Dictionary instead of PostFeedbackRequest record. This is based on the example in their documentation. My guess is that you could create a custom class derived from Dictionary and override .ToString on it so that when ToString is called, it produces the desired output. – Cristian Teodorov Mar 31 '22 at 09:13

0 Answers0