我正在与一个ASP.NET网站工作。我需要从表单中收集数据并将其发送到api。PostAsync()需要两个参数,因此我必须将对象转换为JSON才能发送它。这就是我的麻烦所在,因为api只接收空值。这就是我要看的相关代码:
string apiurl = "http://localhost:5000/";
var content = new StringContent(JsonConvert.SerializeObject(formData), Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.PostAsync($"{apiurl}api/Contact/Create", content))
{
await response.Content.ReadAsStringAsync();
}
}最后,我需要api来接收来自formData对象的值。但是它接收到的值为空。
我无法判断它是否正确地转换为JSON。JsonConvert.SerializeObject( formData )使用我的数据准确地创建一个字符串,而formData对象本身有我的值。但是,当我检查内容变量时,我在任何地方都找不到该字符串。
这是api头:
[HttpPost]
[Route("Create")]
public async Task<IActionResult> Create(string listId, string email, string firstName, string lastName)我如何:
1-确认json是正确的?
2-向api发送非空值?
编辑:
按照要求,我在这里开设了一门课:
public class Report
{
public string listId { get; set; }
public string email { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
}以及我是如何创建对象的:
Report formData = new Report {
listId = listId,
email = getFormValueFromKey(formModel.fieldNameValuePairs, "Email"),
firstName = "None",
lastName = "None"
};发布于 2021-11-04 21:39:10
由于您使用的是格式数据,而且API参数看起来类似于键值对,所以我建议您尝试application/x-www-form-urlencoded内容类型。
var content = new FormUrlEncodedContent(formData);
var response = await PostAsync($"{apiurl}api/Contact/Create", content);
if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<object>(stringData);
}否则,您将需要创建一个视图模型并使用frombody属性。
更新
不幸的是我看不见你的表格数据。但是,如果它已经不是键值对,您可以将它转换为字典,或者更好地发布它,以便我们可以更好地使用它。
var content = new FormUrlEncodedContent(
new Dictionary<string, string>()
{
{"listId", formData.listId},
{"email", formData.email}
}
);或者,如果要使用json,则创建视图模型。
public class Report
{
public string listId {get; set;}
public string email {get; set;}
.....
}和api
[HttpPost]
[Route("Create")]
public async Task<IActionResult> Create([FromBody] Report model)和代码
var json = JsonConvert.SerializeObject(formdata);
var content= new StringContent(json, Encoding.UTF8, "application/json");https://stackoverflow.com/questions/69845813
复制相似问题