c# - 如何序列化我的课程以使用 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
类,还尝试将模型更改为单一投诉,但我无法让它工作,我错过了什么或如何让它工作?
解决方案
这个答案可能来得很晚。但最近我正在研究一个类似的用例。下面的代码对我有用。
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);
推荐阅读
- amazon-web-services - 通过其他 aws 帐户中的中转网关连接本地网络?
- ffmpeg - 将音频文件与图像连接起来
- python - 无法在 Python 中使用多线程刮板正确读取 input.txt 文件
- python - Python os.remove() 不适用于 heruku
- python - 如何在不同的烧瓶微服务中处理身份验证
- .htaccess - 仅针对某些特定页面将非 www/http 强制为 www/https
- security - 处理非法连接/请求的高压情况
- javascript - 热重载不起作用。Webpack 不会在浏览器中重新加载页面
- javascript - 如何在 Visual Studio 的 Blazor WebAssembly 应用程序中将 JS 代码更改传播到 Chrome
- android - 在模拟器上使用 Unreal intstall 构建的 android apk 失败 - INSTALL_FAILED_NO_MATCHING_ABIS