首页 > 解决方案 > 如何序列化我的课程以使用 refit 将其作为 urlencoded 发送

问题描述

嗨,我正在尝试发送一个带有改装的 POST 方法,到目前为止我可以说它正在工作,如果我使用 x-www-form-encoded 选项发送数据,我发送的 json 看起来像这样

{
  "apt": "APT",
  "apartment": "A103",
  "author": "Someone",
  "is_public": "True",
  "is_complaint": "True",
  "show_name": "True",
  "title": "fhj",
  "details": "vvkko"
}

我在视觉工作室和我的模型中构建了我的课程以将其粘贴到 json

namespace App.Models
{
    public class ManyComplaints
    {
        public SingleComplaint data { get; set; }
    }
    public class SingleComplaint
    {
        public string apt { get; set; }
        public string apartment { get; set; }
        public string author { get; set; }
        public string is_public { get; set; }
        public string is_complaint { get; set; }
        public string show_name { get; set; }
        public string title { get; set; }
        public string details { get; set; }
    }

}

在这里我不确定我是否做对了这是我的 api 调用者

 [Headers("Content-Type: application/x-www-form-urlencoded")]
 [Post("/api/complaints/")]
 Task SubmitComplaint([Body(BodySerializationMethod.UrlEncoded)]SingleComplaint complaint);

这是发送数据的代码

public async Task Post()
{
    SingleComplaint data = new SingleComplaint 
    {
        is_public = ShowPost,
        is_complaint = Complaint,
        show_name = ShowName,
        author = Preferences.Get("UserName", null),
        apt0 = Preferences.Get("Apt", null),
        apartment = Preferences.Get("Apartment", null),
        title = TitleEntry.Text,
        details = DetailsEntry.Text
    };

    try
    {                
        var myApi = RestService.For<IApiService>(Constants.webserver);
        var serialized = JsonConvert.SerializeObject(data);
        ManyComplaints complaint = await myApi.SubmitComplaint(data);
        await DisplayAlert("Thanks", "Your message has been succesfully delivered", "Ok");
    }
    catch (Exception ex)
    {
        await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "Ok");
    }
}

尝试使用该行string complaint = await myApi.SubmitComplaint(serialized);并将其更改为字符串而不是ManyComplaints类,还尝试将模型更改为单一投诉,但我无法让它工作,我错过了什么或如何让它工作?

标签: c#jsonserializationxamarin.formsrefit

解决方案


这个答案可能来得很晚。但最近我正在研究一个类似的用例。下面的代码对我有用。

API 声明(使用 Refit)

[Headers("Content-Type: application/x-www-form-urlencoded")]
[Get("")]
public HttpResponseMessage GetData([Body(BodySerializationMethod.UrlEncoded)] FormUrlEncodedContent content);

调用 API

List<KeyValuePair<string, string>> contentKey = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("apt", "APT"),
    new KeyValuePair<string, string>("apartment", "A103"),
    new KeyValuePair<string, string>("author", "Someone")
};

FormUrlEncodedContent content = new FormUrlEncodedContent(contentKey);

HttpResponseMessage response = someClass.GetData(content);

推荐阅读