我正在尝试将编码的消息数据(application / x-www-form-urlencoded)发送到我的Restsharp请求,但是我收到了错误的请求错误消息

时间:2019-04-19 20:22:29

标签: restsharp xunit

我的请求方法:发布

Content-type : application/x-www-form-urlencoded,
using  HttpUtility.UrlEncode(RequestBody);

我在这里遇到一个问题,因为我正将我的Json主体转换为UrlEncode,因此我将它作为字符串发送给我的RestSharp请求,如下所示。

\\Request Model
public class Request
    { 
        public string MessageId { get; set; }
        public bool IsOffline { get; set; }
        public string LanguageCode { get; set; }
        public string MessageType { get; set; }
    }
\\xUnit 
[Fact]
        public void Login()
        {

            Request request = new Request
            {
                MessageId = Guid.NewGuid().ToString(),
                MessageType = "KioskLogin",
                IsOffline = false,
                LanguageCode = "en"
            };
            String RequestBody = JsonConvert.SerializeObject(request);

            //url encode the json
            var payload = String.Format("payload={0}", HttpUtility.UrlEncode(RequestBody));

            IRestResponse response = _restServices.PostRequest(payload);

            Response parsedResponse = JsonConvert.DeserializeObject<Response>(response.Content);

            response.StatusCode.Should().Be(HttpStatusCode.OK);
\\I Builded this RestSharp code Like
    public IRestResponse PostRequest(String Request)
        {
            var restClient = new RestClient(ConfigurationReader.Get("Environment:QA:Endpoint"));
            var request = new RestRequest(Method.POST);

            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            request.AddJsonBody(payload);

            IRestResponse response = restClient.Execute(request);
            return response;
        }

我可以使用HttpUtility.UrlEncode(RequestBody)以URLEncoded形式发送请求,但是我在请求中遇到了问题 "payload=%7B%0A%22MessageId%22%3A%20%222e55dcdf-d877-4970-870e-fef841aff9a1%22%2C%0A%09%22MessageType%22%3A%20%22Login%22%2C%0A%22IsOffline%22%3A%20false%2C%0A%09%22LanguageCode%22%3A%20%22es%22%0A%7D"

但是我不需要那个在“”中,我需要像这样 payload=%7B%0A%22MessageId%22%3A%20%222e55dcdf-d877-4970-870e-fef841aff9a1%22%2C%0A%09%22MessageType%22%3A%20%22Login%22%2C%0A%22IsOffline%22%3A%20false%2C%0A%09%22LanguageCode%22%3A%20%22es%22%0A%7D 如果是这样,那么我会正确获得响应。

1 个答案:

答案 0 :(得分:0)

request.AddParameter("Payload", payload, ParameterType.RequestBody);发送请求正文到request.AddJsonBody(payload);发送请求正文时,我得到了成功响应。