【发布时间】:2025-12-22 02:35:07
【问题描述】:
我有一个发布到 WebAPI 的 MVC 项目。当使用重音字符 (é) 时,WebAPI [FromBody] 的对象为空。当没有重音字符时,它会正确填充。无论哪种方式,MVC 对象都是正确的,所以我不知道为什么会出现从 JSON 到我的 API 对象的转换问题。 JSON 由 Newtonsoft.Json.JsonConvert.SerializeObject 版本 6.0.1 生成。
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _authorizationString);
string json = Newtonsoft.Json.JsonConvert.SerializeObject(model);
var response = await client.PostAsync(_url, new StringContent(json, System.Text.Encoding.Default, "application/json"));
string content = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
model = JsonConvert.DeserializeObject<Model>(content);
TempData["Model"] = model;
return RedirectToAction("Confirmation");
}
}
//API
[HttpPost]
public HttpResponseMessage ApiMethod([FromBody] ApiObject obj)
{
//obj is null here, but only when there is an accent in one of the obj string properties.
...
}
我又发现了一件事。我可以使用 Fiddler 成功发布到 API。我从这一行复制了 JSON,string json = Newtonsoft.Json.JsonConvert.SerializeObject(model);
那么也许 PostAsync 有错误?
【问题讨论】:
-
显示控制器操作的代码。
标签: json asp.net-web-api diacritics