【问题标题】:Invalid request parameters请求参数无效
【发布时间】:2020-02-05 14:10:58
【问题描述】:

下午好,我一直在用 C# 做一个小开发,用于 HTTP POST 中的请求。

我有以下问题,在 c# 中尝试时,以下对我不起作用

using RestSharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;

namespace App_Llamadas_API
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [Obsolete]
        private void button1_Click(object sender, EventArgs e)
        {
            //URL:
            var client = new RestClient("Hidden URL");
            var request = new RestRequest("/", Method.POST);

            //Headers:
            request.AddHeader("X-Authorization", "Hidden Token");
            request.AddHeader("Content-Type", "application/json");

            //Body json:
            request.AddParameter(
            "application/json",
            "{ \"taskRelativePath\": \"My Tasks\\VPN.atmx\", \"botRunners\": [{ \"client\": \"DESKTOP -Hidden name\", \"user\": \"botrunner03\"}], \"runWithRDP\": \"true\" }", // <- your JSON string
             ParameterType.RequestBody);

            IRestResponse response = client.Execute(request);

            var content = response.Content;

            txtResponse.Text = content;

        }

    }
}

回复:{"code":"json.deserialization.exception","details":null,"message":"无效请求参数"}

【问题讨论】:

  • JSON 不允许使用反斜杠。尝试:'{ "taskRelativePath": "My Tasks\\VPN.atmx", "botRunners": [{ "client": "DESKTOP -Hidden name", "user": "botrunner03"}], "runWithRDP": "真的”}'
  • \"runWithRDP\": \"true\" 我的第一个猜测是这个参数需要一个布尔值,而您正在传递一个字符串值。将此更改为 \"runWithRDP\": true 并重新运行
  • 我试过了,但没用,我之前用另一个api试过,它是这样工作的:ibb.co/Dw0vHMF 选项一有效,选项二无效
  • ibb.co/CbKNdky TravisActon 已经试过了,看同样的错误又出现了
  • 我在邮递员上试过这个,它工作正常ibb.co/XSZBs3v

标签: c# json http post restsharp


【解决方案1】:

请求无效,因为 JSON 未正确转义。您需要转义 My Tasks\\VPN 中的每个反斜杠。

"{ \"taskRelativePath\": \"My Tasks\\\\VPN.atmx\", \"botRunners\": [{ \"client\": \"DESKTOP -Hidden name\", \"user\": \"botrunner03\"}], \"runWithRDP\": \"true\" }");

否则它将读取 JSON 如下(注意只有一个反斜杠):

{
  "taskRelativePath": "My Tasks\VPN.atmx",  <-- invalid JSON
  "botRunners": [
    {
      "client": "DESKTOP -Hidden name",
      "user": "botrunner03"
    }
  ],
  "runWithRDP": "true"
}

使用 RestSharp,您可能希望使用 request.AddJsonBody 来构建您的 JSON 有效负载,因为它就是为此而生的,您不必担心引号。这将使用 SimpleJson 序列化对象。

request.AddJsonBody(new
{
    taskRelativePath = "My Tasks\\\\VPN.atmx",
    botRunners = new[]
    {
        new { client = "DESKTOP -Hidden name", user = "botrunner03" }
    },
    runWithRDP = "true",
});

【讨论】:

    猜你喜欢
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多