You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI应用POST请求报JSON意外令牌错误,求排查代码问题

问题排查与修复建议

从你提供的代码和报错信息来看,POST请求失败并触发"JSON输入存在意外令牌"错误,大概率是请求内容格式不匹配或请求路径/客户端配置异常导致的,以下是具体排查点:

1. 序列化格式与API端模型绑定不兼容

你用Newtonsoft.Json序列化Operation类,但.NET 6 API默认使用System.Text.Json进行模型绑定,两者的默认序列化规则存在差异:

  • Newtonsoft.Json默认保留类属性的PascalCase命名(比如EmployeeID)
  • System.Text.Json默认将属性转换为驼峰命名(比如employeeID)

如果API端的Operation模型字段命名和序列化后的JSON字段不匹配,就会导致后端无法解析JSON,抛出格式错误。

修复方法:

  • 统一序列化规则:在MAUI端用Newtonsoft.Json指定驼峰序列化:
    var input = JsonConvert.SerializeObject(op, new JsonSerializerSettings
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    });
    
  • 或者在API端配置System.Text.Json支持PascalCase:
    // Program.cs中
    builder.Services.AddControllers()
        .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
        });
    

2. 请求路径拼接错误

client.BaseAddress和PostAsync的路径拼接可能出现双斜杠问题:
如果ApiBaseUrl的结尾是/(比如http://localhost:5000/),加上PostAsync的/api/workassignments,最终请求路径会变成http://localhost:5000//api/workassignments,这种无效路径会导致后端返回404页面(HTML内容),前端解析HTML时就会报"JSON意外令牌"。

修复方法:
确保ApiBaseUrl结尾不带斜杠,或者PostAsync的路径开头不带斜杠,二选一即可:

// 方式一:BaseAddress结尾无斜杠
client.BaseAddress = new Uri("http://localhost:5000");
HttpResponseMessage message = await client.PostAsync("/api/workassignments", content);

// 方式二:PostAsync路径开头无斜杠
client.BaseAddress = new Uri("http://localhost:5000/");
HttpResponseMessage message = await client.PostAsync("api/workassignments", content);

3. 调试模式下的HTTPS客户端处理器问题

如果你的本地API使用HTTP协议(而非HTTPS),调试模式下的HttpsClientHandlerService可能强制使用HTTPS,或者证书验证失败,导致请求未到达后端,而是返回错误页面(非JSON内容),引发解析报错。

修复方法:
调试时暂时跳过证书验证(仅本地开发场景使用),在HttpsClientHandlerService的GetPlatformMessageHandler方法中添加逻辑:

#if ANDROID
var handler = new Xamarin.Android.Net.AndroidMessageHandler();
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
#elif IOS
var handler = new NSUrlSessionHandler();
handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, errors) => true;
#endif
return handler;

或者给本地API启用HTTPS,并确保MAUI客户端信任该证书。

4. 序列化后的JSON合法性验证

先打印序列化后的input内容,确认是否是合法的JSON:

var input = JsonConvert.SerializeObject(op);
Console.WriteLine(input); // 查看输出是否符合预期,有没有null值、循环引用或格式错误

比如lat/lon如果是无效的数值(比如字符串而非数字),也会导致后端解析失败。

5. 异步方法调用问题

确保调用这段POST代码的方法标记了async,并正确使用await,否则可能导致异步操作未完成,请求未正常发送:

private async Task SendOperationAsync()
{
    // 你的POST代码...
    HttpResponseMessage message = await client.PostAsync("/api/workassignments", content);
}

内容的提问来源于stack exchange,提问作者Simo Siren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 13:57:35