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

调用RestRequest未获取到IRestResponse?求技术指导

Hey there! Let's figure out why you're not getting any content in txtResponse after calling the SureDone API. Looking at your code, there are a few key issues that are likely causing this problem. Let's break them down one by one:

1. You're reusing and accumulating payload across rows

Right now, you initialize payload once before the loop, then keep adding to it for every row. That means each API request is sending all previous rows' data plus the current one—this is definitely not what you want, and the API is probably rejecting this malformed request, resulting in an empty response.

2. Manual multipart/form-data formatting is error-prone

You're manually building the multipart payload with a formBoundary set to "undefined", which is invalid. Worse, you're setting the content-type to application/x-www-form-urlencoded but sending multipart data—this mismatch will confuse the API server. The good news is RestSharp can handle form data automatically, so you don't need to do this manual string building!

3. RestClient/RestRequest are being recreated unnecessarily

Creating a new RestClient and RestRequest inside the loop isn't a huge issue, but it's inefficient. More importantly, you're not resetting the request parameters for each row, so old data might be leaking into subsequent requests.

4. You're overwriting txtResponse on every row

Each iteration of the loop sets txtResponse.Text = response.Content, so only the last row's response will be shown. If the last request fails or returns empty, you'll see nothing even if earlier requests worked.


Fixed Code

Here's a revised version of your code that addresses all these issues:

private void btnLoad_Click(object sender, EventArgs e)
{
    string PathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtChooseFile.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
    OleDbConnection conn = new OleDbConnection(PathConn);
    OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [" + txtLoad.Text + "$]", conn);
    DataTable dt = new DataTable();
    da.Fill(dt);
    dataGridView.DataSource = dt;

    // Create RestClient once outside the loop for efficiency
    var client = new RestClient("https://www.api.suredone.com/v1/editor/items/add");

    // Clear response box first
    txtResponse.Text = "";
    string allPayloads = "";

    foreach (DataRow row in dt.Rows)
    {
        try
        {
            // Create a new RestRequest for each row to avoid cross-contamination
            var request = new RestRequest(Method.POST);
            request.AddHeader("x-auth-token", "tokenString");
            request.AddHeader("x-auth-user", "username");

            // Let RestSharp handle form data automatically (no manual payload building!)
            request.AddParameter("action", row["action"].ToString());
            request.AddParameter("sku", row["sku"].ToString());
            request.AddParameter("stock", row["stock"].ToString());
            request.AddParameter("price", row["price"].ToString());
            request.AddParameter("msrp", row["msrp"].ToString());
            request.AddParameter("title", row["title"].ToString());
            request.AddParameter("longDescription", row["longdescription"].ToString());
            request.AddParameter("condition", row["condition"].ToString());
            request.AddParameter("brand", row["brand"].ToString());
            request.AddParameter("notes", row["notes"].ToString());

            // Execute the request
            IRestResponse response = client.Execute(request);

            // Append response to txtResponse instead of overwriting
            if (response.IsSuccessful)
            {
                txtResponse.Text += $"Success for SKU {row["sku"]}: {response.Content}\n\n";
            }
            else
            {
                txtResponse.Text += $"Error for SKU {row["sku"]}: Status Code {response.StatusCode}, Details: {response.ErrorMessage}\n\n";
            }

            // Save payload for reference (optional - requires Newtonsoft.Json NuGet package)
            var payloadDict = request.Parameters.ToDictionary(p => p.Name, p => p.Value);
            allPayloads += $"SKU {row["sku"]} Payload:\n{Newtonsoft.Json.JsonConvert.SerializeObject(payloadDict, Newtonsoft.Json.Formatting.Indented)}\n\n";
        }
        catch (Exception ex)
        {
            txtResponse.Text += $"Exception for SKU {row["sku"]}: {ex.Message}\n\n";
        }
    }

    txtProducts.Text = allPayloads;
}

Key Improvements:

  • No manual payload building: Uses request.AddParameter to let RestSharp handle the correct content-type and formatting automatically.
  • Efficient client reuse: Creates one RestClient instance instead of a new one per row.
  • Better error visibility: Catches exceptions and checks request success status, so you can see exactly what went wrong for each product.
  • Preserves all responses: Appends each row's result to txtResponse instead of overwriting it.
  • Readable payload logging: Serializes the request parameters to formatted JSON for easier debugging (remove this part if you don't need it, or add the Newtonsoft.Json NuGet package to use it).

Additional Tips:

  • Double-check that your tokenString and username are valid and correctly entered.
  • Confirm parameter names match the SureDone API docs (e.g., is it longdescription or longDescription? Your code uses both—make sure this aligns with what the API expects).
  • Test a single row's data in a tool like Postman first to verify your credentials and parameters work outside of your C# code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:03:05