无效的请求参数

问题描述 投票:0回答:1

下午好,我一直在用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,“消息”:“无效的请求参数”}]

c# json http post restsharp
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.