本文整理汇总了C#中RestSharp.RestRequest.AddJsonBody方法的典型用法代码示例。如果您正苦于以下问题:C# RestRequest.AddJsonBody方法的具体用法?C# RestRequest.AddJsonBody怎么用?C# RestRequest.AddJsonBody使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类RestSharp.RestRequest
的用法示例。
在下文中一共展示了RestRequest.AddJsonBody方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendRequest
public object SendRequest(string path, Method method, object jsonRequest)
{
RestClient client = new RestClient(APSController);
RestRequest request = new RestRequest(path, method);
//let's ignore the certificate error from the APSC
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
request.AddHeader("APS-Token", APSToken);
request.AddJsonBody(jsonRequest);
var result = client.Execute(request);
dynamic jsonResponse = Newtonsoft.Json.Linq.JObject.Parse(result.Content);
if(result.StatusCode.GetHashCode() >= 300)
throw new Exception(result.ErrorMessage);
if (result.StatusCode == HttpStatusCode.OK)
return jsonResponse;
return null;
}
示例2: crearDetallePlantilla
private void crearDetallePlantilla(Plantilla pPlantilla)
{
List<int> ids = (List<int>)HttpContext.Current.Session["IdsPreguntaPlantilla"];
List<Pregunta> preguntas = new List<Pregunta>();
foreach (int valor in ids) {
RestClient client = new RestClient(ConfigurationManager.AppSettings.Get("endpoint"));
RestRequest request = new RestRequest("Preguntas/{id}", Method.GET);
request.AddUrlSegment("id", Convert.ToString(valor));
var response = client.Execute(request);
string json = response.Content;
Pregunta nuevaPregunta = JsonConvert.DeserializeObject<Pregunta>(json);
preguntas.Add(nuevaPregunta);
}
RestClient client2 = new RestClient(ConfigurationManager.AppSettings.Get("endpoint"));
foreach (Pregunta item in preguntas) {
RestRequest request2 = new RestRequest("PlantillaDetalle/", Method.POST);
PlantillaDetalle x = new PlantillaDetalle(0, pPlantilla, item);
request2.AddJsonBody(x);
var response = client2.Execute(request2);
Console.WriteLine(response.Content.ToString());
}
}
示例3: GetById_ShouldReturnStatusCodeOk
public void GetById_ShouldReturnStatusCodeOk()
{
var postRequest = new RestRequest(ResourceName, Method.POST);
var expectedIngredient = new IngredientModel
{
Name = "ingredient1",
Price = 123
};
postRequest.AddJsonBody(expectedIngredient);
var postResponse = Client.Execute(postRequest);
Assert.That(postResponse, Is.Not.Null);
Assert.That(postResponse.StatusCode, Is.EqualTo(HttpStatusCode.Created));
var ingredientModel = _jsonDeserializer.Deserialize<IngredientModel>(postResponse);
var getRequest = new RestRequest(ResourceNameWithParameter, Method.GET);
getRequest.AddUrlSegment("id", ingredientModel.Id.ToString());
var getResponse = Client.Execute(getRequest);
Assert.That(getResponse, Is.Not.Null);
Assert.That(getResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var returnedIngredientModel = _jsonDeserializer.Deserialize<IngredientModel>(getResponse);
Assert.That(returnedIngredientModel, Is.Not.Null);
Assert.That(returnedIngredientModel.Id, Is.EqualTo(ingredientModel.Id));
}
示例4: btnCrear_Click
protected void btnCrear_Click(object sender, EventArgs e)
{
if (validarCampos())
{
RestClient client = new RestClient(ConfigurationManager.AppSettings.Get("endpoint"));
RestRequest request = new RestRequest("kpis/", Method.POST);
List<DetalleFormula> formulaCompleta = new List<DetalleFormula>();
for (int i = 0; i < formula.Count; i++)
{
formulaCompleta.Add(new DetalleFormula(i, variables[i], formula[i]));
}
KPI kpiNuevo = new KPI(0, txtDescripcion.Text, ddlFormato.Text, Convert.ToDouble(txtObjetivo.Text), ddlPeriodicidad.Text, new ParametroKPI(Convert.ToInt32(ddlLimiteInf.Text), Convert.ToInt32(ddlLimiteSup.Text)), formulaCompleta);
request.AddJsonBody(kpiNuevo);
var response = client.Execute(request);
formula = new List<string>();
variables = new List<string>();
operador = false;
Response.Redirect("indicadoresKPI.aspx");
}
else
{
//"error"
}
}
示例5: SaveWidget
public static async Task<IRestResponse<ResultValue>> SaveWidget(string widgetString)
{
var request = new RestRequest(SystemResource.SaveWidgetRequest, Method.POST);
request.AddJsonBody(widgetString);
return await Client.ExecutePostTaskAsync<ResultValue>(request);
}
示例6: Main
static void Main(string[] args)
{
while (true) {
string choice;
string id;
int status;
var client = new RestClient("http://192.168.0.3:1337/auto/api/v1.0/");
var request = new RestRequest("relays", Method.GET);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = client.Execute<Relay>(request);
var RelayCollection = client.Execute<RelayCollection>(request);
Console.WriteLine(RelayCollection.Content);
Console.WriteLine("What id do you want to change?");
id = Console.ReadLine();
Console.WriteLine("We will change id:{0}\nwhat do you want to do?\n0 = off 1 = on", id);
choice = Console.ReadLine();
if(choice == "1")
{
status = 1;
}
else
{
status = 0;
}
var putRequest = new RestRequest("relays/" + id, Method.PUT);
putRequest.AddJsonBody(new { status = status });
client.Execute(putRequest);
}
}
示例7: Flush
public void Flush(Workspace workspace)
{
ConsoleEx.Info($"Running sink: {this.GetType().Name}");
var request = new RestRequest(@"api/workspaces", Method.POST);
request.AddJsonBody(workspace);
request.RequestFormat = DataFormat.Json;
var restClient = new RestClient(serviceUri);
var response = restClient.Post(request);
if(response.StatusCode == HttpStatusCode.OK)
{
ConsoleEx.Ok("Workspace analysis report published.");
var locationHeader = response.Headers.FirstOrDefault(h=> h.Name == "Location");
if (locationHeader != null)
{
string workspaceLocation = locationHeader.Value.ToString().ToLower();
ConsoleEx.Ok($"Visit {workspaceLocation}");
}
}
else
{
ConsoleEx.Error($"Workspace not published to target sink.");
ConsoleEx.Error($"Status: {response.StatusCode}, Response: {response.Content}");
}
}
示例8: Send
public IRestResponse Send(string text)
{
var client = new RestClient(_slackApiUrl);
var request = new RestRequest(Method.POST);
request.AddJsonBody(new payload {text = text});
return client.Execute(request);
}
示例9: Should_update_users_status
public void Should_update_users_status()
{
var url = string.Format("https://{0}/v2", EndpointHost);
var client = new RestClient(url);
var request = new RestRequest("/user/" + RestSharp.Contrib.HttpUtility.UrlEncode(Email), Method.PUT);
request.AddQueryParameter("auth_token", Token);
var user = new HipChatUser()
{
name = "",
email = Email,
presence = new Presence()
{
status = "blah",
show = "away"
},
mention_name = ""
};
request.AddJsonBody(user);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Content-type", "application/json");
request.AddHeader("Accept", "application/json");
var response = client.Execute(request);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
示例10: Post
public virtual dynamic Post(AuthRequestModel model)
{
var request = new RestRequest(Method.POST);
if (string.IsNullOrEmpty(model.client_id))
{
model.client_id = ClientId;
}
if (string.IsNullOrEmpty(model.grant_type) && GrantTypeDetection)
{
model.grant_type = DetectGrantType(model);
}
request.AddJsonBody(model);
var response = restClient.Execute<AuthorizationResponse>(request);
if (response.ErrorException == null && response.StatusCode.Equals(HttpStatusCode.OK))
{
return Json(response.Data);
}
else
{
var responseProxy = new HttpResponseMessage(response.StatusCode);
var mimeType = new System.Net.Mime.ContentType(response.ContentType);
responseProxy.Content = new StringContent(response.Content, System.Text.Encoding.GetEncoding(mimeType.CharSet), mimeType.MediaType);
return responseProxy;
}
}
示例11: Send
/// <summary>
/// Sends the formatted messages.
/// </summary>
/// <param name="messages">The messages to send.</param>
/// <param name="succeededAction">A success action that should be called for successfully sent messages.</param>
/// <param name="failedAction">A failure action that should be called when a message send operation fails.</param>
public void Send(IEnumerable<ProviderNotificationMessage> messages,
Action<ProviderNotificationMessage> succeededAction,
Action<ProviderNotificationMessage, Exception> failedAction)
{
foreach (var message in messages)
{
try
{
// create a new rest request and add the message to the http message body
var request = new RestRequest(Method.POST);
request.AddJsonBody(message);
// send the POST request and call success action if everything went fine
_client.Post<ProviderNotificationMessage>(request);
if (succeededAction != null)
succeededAction(message);
}
catch(Exception e)
{
// if the post fails call the failedAction
if(failedAction != null)
failedAction(message, e);
}
}
}
示例12: CreateRecipient
public OnfleetRecipient CreateRecipient(string name, string phone, string notes, bool skipSMSNotifications,
bool skipPhoneNumberValidation)
{
var recipient = new OnfleetRecipient()
{
name = name,
phone = "+1" + phone,
notes = notes,
skipPhoneNumberValidation = skipPhoneNumberValidation,
skipSMSNotifications = skipSMSNotifications
};
var request = new RestRequest("recipients", Method.POST);
request.JsonSerializer.ContentType = "application/json; charset=utf-8";
request.AddHeader("Content-Type", "application/json");
request.AddJsonBody(recipient);
var response = _client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
return JsonConvert.DeserializeObject<OnfleetRecipient>(response.Content);
}
else
{
_logger.ErrorFormat("Onfleet Create Recipient : {0}", response.ErrorMessage);
return null;
}
}
示例13: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
var client = new RestClient("http://www.soawebservices.com.br/restservices/test-drive/cdc/pessoafisicasimplificada.ashx");
var request = new RestRequest(Method.POST);
// Credenciais de Acesso
Credenciais credenciais = new Credenciais();
credenciais.Email = "seu email";
credenciais.Senha = "sua senha";
// Requisicao
Requisicao requisicao = new Requisicao();
requisicao.Credenciais = credenciais;
requisicao.Documento = "99999999999";
requisicao.DataNascimento = "01/01/1900";
// Adiciona Payload a requisicao
request.AddJsonBody(requisicao);
IRestResponse<Simplificada> response = client.Execute<Simplificada>(request);
Simplificada simplificada = new Simplificada();
simplificada = response.Data;
if (simplificada.Status == true)
{
this.nome.InnerText = simplificada.Nome;
}
else
{
this.nome.InnerText = String.Format("Ocorreu um erro: {}", simplificada.Mensagem);
}
}
示例14: ChangeState
private async Task ChangeState(LifxHttpLight light, object payload)
{
var client = new RestClient(BaseUrl);
var request = new RestRequest($"v1/lights/{light.Id}/state");
request.AddHeader("Authorization", $"Bearer {_token}");
request.AddJsonBody(payload);
await client.PutTaskAsync<object>(request);
}
示例15: CreateAsync
/// <summary>
/// Creates an agreement. Sends it out for signatures, and returns the agreementID in the response to the client
/// </summary>
/// <param name="info"></param>
public virtual Task<AgreementCreationResponse> CreateAsync(AgreementCreationInfo info)
{
var request = new RestRequest(Method.POST);
request.JsonSerializer = new Serialization.NewtonSoftSerializer();
request.Resource = "agreements";
request.AddJsonBody(info);
return this.Sdk.ExecuteAsync<AgreementCreationResponse>(request);
}