我正在使用httpclient来调用端点,这对我来说很好。但我需要使用restsharp restclient对象来调用端点。我怎样才能做到这一点?以下是使用http客户端postasync的代码。
//输入参数和请求标题
string userID = "testuser";
string memberId = "001";
string baseURL = "https://www.test.com";
string urlParameters ="TestServices/GetAll/{0}/{1}/{2}/{3}/{4}/{5}";
string contentType = "application/json";
string role = "USER";
string Caller = "PREVIEW";
string ticks = DateTime.Now.Ticks.ToString();
string systemId = "613e70b3-e3ec-4205-bcd6-094d6a9f7a41";
string encryptedToken = “XXXXXXXXXXXXXXXXXXXX”
string sessionID = "8303d34a-5c8a-4984-9bf9-4ba39be21352";
//要作为stringcontent发送的数据
string postData = "{\"TheContentAreas\":[{\"ControlTypeID\":\"230c5669-aa0d-41bc-9069-559b5e7d0ece\",\"PlaceholderID\":\"a16a471e-9416-43fc-8ceb-fddb97509e0c\"}]}";
string response = string.Empty;
//调用终点
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseURL);
client.DefaultRequestHeaders.Add("Authorization", "XXXXXXXXXXXXXXXXXXXXXXX");
client.DefaultRequestHeaders.Add("Session", sessionID);
client.DefaultRequestHeaders.Add("EncryptedKey", encryptedToken);
try
{
HttpResponseMessage resp = client
.PostAsync(string.Format(urlParameters, role, systemId, Caller, ticks, userID, memberId),
new StringContent(postData, System.Text.Encoding.UTF8, "application/json")).Result;
if (resp.IsSuccessStatusCode)
{
response = resp.Content.ReadAsStringAsync().Result;
}
}
答案 0 :(得分:0)
我花了一些时间研究它,这是我的解决方案。
我创建了一个通用服务调用者类,并从我的主类中调用它。
//Main class calling the service invoker
try
{
var _restMethodInvoker = new RestEndPointInvoker();
var headers = new Dictionary<string, string>
{
{ "Authorization", "xxx" },
{ "Session", "xxx" } ,
{ "EncryptedKey", "xxx"}
};
var inputParameters = new Dictionary<string, string>
{
{ "Role", "MEMBER" },
{ "SystemID", "xxx" } ,
{ "Caller", "PREVIEW" } ,
{ "Ticks", "1234" } ,
{ "UserID", "TestUser" } ,
{ "MemberId", "TestMEmber" }
var request1 = new RestClientRequest
{
_apiMethod = "TestServices/GetAll/{Role}/{SystemID}/{Caller}/{Ticks}/{UserID}/{MemberId}",
_environmentType = "xx",
_inputParameters = inputParameters,
_requestHeaders = headers
};
var result1 = _restMethodInvoker.GetAsync<List<ReturnType>>(request1);
var result = result1.Result;
}
catch (Exception ex)
{
throw ex;
}
使用restsharp
重新启动Invoker类namespace RestServiceInvoker
{
public class RestEndPointInvoker : IRestEndPointInvoker
{
public RestEndPointInvoker()
{
_httpClient = new RestClient();
}
private void BuildRestClient(RestClientRequest request)
{
//Set the headers
foreach (var header in request._requestHeaders)
{
_httpClient.AddDefaultHeader(header.Key, header.Value);
}
}
public async Task<IRestResponse<T>> GetAsync<T>(RestClientRequest request) where T: new()
{
//Build the client object
BuildRestClient(request);
//Build request object
var restRequest = BuildRestReqestObject(request);
//var response11 = _httpClient.Execute<T>(restRequest);
var taskSource = new TaskCompletionSource<IRestResponse<T>>();
//Execute the request
_httpClient.ExecuteAsync<T>(restRequest, response =>
{
if (response.ErrorException != null)
taskSource.TrySetException(response.ErrorException);
else
taskSource.TrySetResult(response);
});
return await taskSource.Task;
}
private RestRequest BuildRestReqestObject(RestClientRequest requestObj)
{
var request = new RestRequest {Resource = requestObj._apiMethod};
if (requestObj._inputParameters == null || requestObj._inputParameters.Count <= 0) return request;
foreach (var inputParam in requestObj._inputParameters)
{
request.AddParameter(inputParam.Key, inputParam.Value, ParameterType.UrlSegment);
}
request.Method = Method.POST; //This could be parameterized from the client. For now we are only supporting get calls
//This would be sent as input parameter. Just was lazy to hardcode it here
string jsonToSend = @"xxxxxxxxxxx";
request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
return request;
}
}
}