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

ASP.NET Core 6中调用GraphQL API查询运单返回BadRequest求助

ASP.NET Core 6中GraphQL查询运单详情返回BadRequest错误排查

问题描述

在ASP.NET Core 6中调用GraphQL API获取运单详情时,提交运单ID(如101010)后收到BadRequest错误。期望获取的运单字段包括id、code、customerDue、timeFrom、timeTo、latitude、longitude、collected、paidToCustomer。以下是相关代码,请求协助排查解决。

控制器代码

public IActionResult shipment()
{
    return View();
}

[HttpPost]
public async Task<IActionResult> shipment(int shipmentId)
{
    try
    {
        var query = @"            query {
                shipment(id: " + shipmentId + @") {
                    id
                    code
                    customerDue
                    timeFrom
                    timeTo
                    latitude
                    longitude
                    collected
                    paidToCustomer
                }
            }
        ";

        var request = new HttpRequestMessage(HttpMethod.Post, "http://accuratess.holol-aldiar.com.sa:8000/graphql");
        request.Content = new StringContent(query, System.Text.Encoding.UTF8, "application/json");

        var response = await _httpClient.SendAsync(request);

        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadAsStringAsync();
            var shipmentResponse = JsonConvert.DeserializeObject<Shipment>(result);

            return View(shipmentResponse);
        }
        else
        {
            throw new Exception("Failed to retrieve shipment details. Status code: " + response.StatusCode);
        }
    }
    catch (Exception ex)
    {
        // Handle the exception
        return StatusCode(500, ex.Message);
    }

    return View("shipment");
}

Shipment模型类代码

public class Shipment
{
    public int Id { get; set; }
    public string Code { get; set; }
    public DateTime CustomerDue { get; set; }
    public DateTime TimeFrom { get; set; }
    public DateTime TimeTo { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public bool Collected { get; set; }
    public decimal PaidToCustomer { get; set; }
}

视图代码

@model apiGraphQl.Models.Shipment

<form method="post" asp-action="shipment">
    <label for="shipmentId">Enter Shipment ID:</label>
    <input type="text" asp-for="Id" id="shipmentId" value="@Model" />

    <button type="submit">Get Shipment Details</button>
</form>

可能的错误原因及解决方法

  • GraphQL请求格式错误
    GraphQL的POST请求要求内容是包含query字段的JSON对象,而非纯查询字符串。当前代码直接发送查询字符串,不符合API要求。修改请求内容构造逻辑:

    var query = @"query {
        shipment(id: " + shipmentId + @") {
            id
            code
            customerDue
            timeFrom
            timeTo
            latitude
            longitude
            collected
            paidToCustomer
        }
    }";
    var requestBody = new { query = query };
    var jsonContent = JsonConvert.SerializeObject(requestBody);
    request.Content = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
    
  • 运单ID参数类型不匹配
    如果GraphQL API要求id参数为字符串类型,需给shipmentId添加引号:

    var query = @"query {
        shipment(id: """ + shipmentId + @""") {
            id
            code
            customerDue
            timeFrom
            timeTo
            latitude
            longitude
            collected
            paidToCustomer
        }
    }";
    
  • 视图模型绑定问题
    视图中value="@Model"会输出整个Shipment对象的ToString结果,导致提交的ID格式错误。同时初始GET请求未传入模型,会导致Model为null,修改如下:

    <input type="text" asp-for="Id" id="shipmentId" value="@(Model?.Id ?? 0)" />
    

    并更新GET方法:

    public IActionResult shipment()
    {
        return View(new Shipment());
    }
    
  • JSON反序列化结构不匹配
    GraphQL返回结果通常包含data嵌套字段,需创建对应包装类适配:

    public class ShipmentResponse
    {
        public ShipmentData Data { get; set; }
    }
    
    public class ShipmentData
    {
        public Shipment Shipment { get; set; }
    }
    

    然后修改反序列化代码:

    var shipmentResponse = JsonConvert.DeserializeObject<ShipmentResponse>(result);
    return View(shipmentResponse.Data.Shipment);
    

内容的提问来源于stack exchange,提问作者عالم ديم

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 10:18:10