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

Xamarin安卓模拟器连接本地API出现400 BadRequest错误排查

解决Xamarin连接.NET 4.8本地API报400 BadRequest的问题

核心排查方向(优先从API端入手,因模拟器Chrome访问同样报错)

1. 模型绑定不匹配(400错误最常见原因)

Xamarin端发送VehiculosRequest对象,API端接收VehiculosAndroidRequest,必须确保两个类的字段名完全一致(含大小写)、字段类型匹配、嵌套对象结构相同:

  • 检查SessionID、Datos等核心字段的命名和类型是否完全对应
  • 若存在字段名大小写差异,可在API模型类字段上添加显式映射标记:
// API端 VehiculosAndroidRequest 示例
public class VehiculosAndroidRequest
{
    [JsonProperty("SessionID")] // 匹配Xamarin端发送的字段名
    public string SessionId { get; set; }

    [JsonProperty("Datos")]
    public DatosModel Datos { get; set; }
}

2. .NET 4.8 JSON序列化配置变化

.NET Framework 4.8对ASP.NET MVC的JSON处理有默认调整,需检查Web.config配置是否兼容:
添加或确认以下配置,确保JSON解析正常:

<system.web>
  <compilation debug="true" targetFramework="4.8" />
  <httpRuntime targetFramework="4.8" />
</system.web>

<system.web.extensions>
  <scripting>
    <webServices>
      <jsonSerialization maxJsonLength="50000000">
      </jsonSerialization>
    </webServices>
  </scripting>
</system.web.extensions>

若API默认使用System.Text.Json而非Newtonsoft.Json,可在Global.asax.cs的Application_Start中强制指定Newtonsoft.Json作为格式化器:

protected void Application_Start()
{
    // 其他初始化代码...
    
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings
    {
        ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
        NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
    };
}

3. API路由匹配问题

确保API路由与Xamarin请求路径完全对应,可在控制器和方法上显式添加路由标记:

[RoutePrefix("reservasandroid")]
public class ReservasAndroidController : Controller
{
    [HttpPost]
    [Route("GetVehiculosPrecios")]
    public JsonResult GetVehiculosPrecios(VehiculosAndroidRequest request)
    {
        // 原有代码...
    }
}

4. SSL/HTTPS配置问题

虽然已处理证书验证,但.NET 4.8对HTTPS要求更严格,可先切换到HTTP测试:

  • 修改API启动设置为HTTP,调整Xamarin端BaseAddress为http://10.0.2.2:44365/reservasandroid/
  • 若HTTP能正常访问,再排查HTTPS证书信任问题,或在API Web.config中添加宽松SSL配置(仅用于测试)

Xamarin端辅助检查

  • 输出序列化后的JSON字符串,确认请求格式正确:
string datosToJson = JsonConvert.SerializeObject(datosRequest);
Console.WriteLine("Request JSON: " + datosToJson);
  • 替换同步调用为异步模式,避免死锁或异常被隐藏:
public async Task<VehiculosPreciosResponse> GetVehiculosPrecio(VehiculosRequest datosRequest)
{
    using (var client = GetLocalInstance())
    {
        string datosToJson = JsonConvert.SerializeObject(datosRequest);
        var content = new StringContent(datosToJson, Encoding.UTF8, "application/json");

        HttpResponseMessage response = await client.PostAsync("GetVehiculosPrecios", content);
        response.EnsureSuccessStatusCode();

        var vehiculosResponse = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<VehiculosPreciosResponse>(vehiculosResponse);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 11:33:45