Programing

RestSharp에서 요청 본문에 텍스트를 추가하는 방법

lottogame 2020. 8. 26. 08:19
반응형

RestSharp에서 요청 본문에 텍스트를 추가하는 방법


RestSharp를 사용하여 웹 서비스를 사용하려고합니다. 지금까지 모든 것이 잘 진행되었지만 (John Sheehan과 모든 기여자들에게 환호합니다!)하지만 저는 걸림돌에 부딪 혔습니다. 이미 직렬화 된 형식 (즉, 문자열)으로 RestRequest 본문에 XML을 삽입하고 싶다고 가정 해 보겠습니다. 이 작업을 수행하는 쉬운 방법이 있습니까? .AddBody () 함수가 뒤에서 직렬화를 수행하므로 내 문자열이 <String />.

어떤 도움이라도 대단히 감사합니다!

편집 : 현재 코드 샘플이 요청되었습니다. 아래 참조-

private T ExecuteRequest<T>(string resource,
                            RestSharp.Method httpMethod,
                            IEnumerable<Parameter> parameters = null,
                            string body = null) where T : new()
{
    RestClient client = new RestClient(this.BaseURL);
    RestRequest req = new RestRequest(resource, httpMethod);

    // Add all parameters (and body, if applicable) to the request
    req.AddParameter("api_key", this.APIKey);
    if (parameters != null)
    {
        foreach (Parameter p in parameters) req.AddParameter(p);
    }

    if (!string.IsNullOrEmpty(body)) req.AddBody(body); // <-- ISSUE HERE

    RestResponse<T> resp = client.Execute<T>(req);
    return resp.Data;
}

요청 본문에 일반 xml 문자열을 추가하는 방법은 다음과 같습니다.

req.AddParameter("text/xml", body, ParameterType.RequestBody);


@dmitreyg의 답변에 추가하고 @jrahhali의 답변에 대한 의견을 추가하려면 현재 버전에서 이것이 게시되는 시점을 기준으로 v105.2.3구문은 다음과 같습니다.

request.Parameters.Add(new Parameter() { 
    ContentType = "application/json", 
    Name = "JSONPAYLOAD", // not required 
    Type = ParameterType.RequestBody, 
    Value = jsonBody
});

request.Parameters.Add(new Parameter() { 
    ContentType = "text/xml", 
    Name = "XMLPAYLOAD", // not required 
    Type = ParameterType.RequestBody, 
    Value = xmlBody
});

참고 URL : https://stackoverflow.com/questions/5095692/how-to-add-text-to-request-body-in-restsharp

반응형