无效的请求参数

时间:2020-02-05 14:10:58

标签: c# json http post restsharp

下午好,我一直在用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;

        }

    }
}

回复:{“代码”:“ json.deserialization.exception”,“详细信息”:null,“消息”:“无效的请求参数”}

1 个答案:

答案 0 :(得分:0)

该请求无效,因为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",
});