client.ExecuteAsync<T> Delegate does not take 1 arguments - c#

I'm trying to change my Restsharp Client to work async instead of sync.
Each of my API-Calls referes to the GetAsync<T> method. When I try now to change the Client to call ExecuteAsync<T> instead of Execute i got this error:
Delegate 'Action, RestRequestAsyncHandle>' does not take 1 Arguments
I'm using RestSharp Version 106.6.10 currently.
Here is my GetAsyncMethod:
public async Task<T> GetAsync<T>(string url, Dictionary<string, object> keyValuePairs = null)
{
try
{
// Check token is expired
DateTime expires = DateTime.Parse(Account.Properties[".expires"]);
if (expires < DateTime.Now)
{
// Get new Token
await GetRefreshTokenAsync();
}
// Get AccessToken
string token = Account.Properties["access_token"];
if (string.IsNullOrEmpty(token))
throw new NullReferenceException("AccessToken is null or empty!");
// Create client
var client = new RestClient()
{
Timeout = 3000000
};
//Create Request
var request = new RestRequest(url, Method.GET);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Authorization", "Bearer " + token);
// Add Parameter when necessary
if (keyValuePairs != null)
{
foreach (var pair in keyValuePairs)
{
request.AddParameter(pair.Key, pair.Value);
}
}
// Call
var result = default(T);
var asyncHandle = client.ExecuteAsync<T>(request, restResponse =>
{
// check respone
if (restResponse.ResponseStatus == ResponseStatus.Completed)
{
result = restResponse.Data;
}
//else
// throw new Exception("Call stopped with Status: " + response.StatusCode +
// " Description: " + response.StatusDescription);
});
return result;
}
catch (Exception ex)
{
Crashes.TrackError(ex);
return default(T);
}
}
Here one of the calling Methods:
public async Task<List<UcAudit>> GetAuditByHierarchyID(int hierarchyID)
{
string url = AuthSettings.ApiUrl + "/ApiMethod/" + hierarchyID;
List<UcAudit> auditList = await GetAsync<List<UcAudit>>(url);
return auditList;
}
When I Change the T in ExecuteAsync<T> in one of my classes the error is gone. How can I change the method to work async with <T>???

With the info from Lasse Vågsæther Karlsen I found the solution.
This is the start:
var asyncHandle = client.ExecuteAsync<T>(request, restResponse =>
{
// check respone
if (restResponse.ResponseStatus == ResponseStatus.Completed)
{
result = restResponse.Data;
}
//else
// throw new Exception("Call stopped with Status: " + response.StatusCode +
// " Description: " + response.StatusDescription);
});
Worked for me :
client.ExecuteAsync<T>(request, (response, asyncHandle )=>
{
//check respone
if (response.StatusCode == HttpStatusCode.OK)
{
result = response.Data;
}
else
throw new Exception("Call stopped with Status: " + response.StatusCode +
" Description: " + response.StatusDescription);
});
Thank you!

Related

Trying to move the output of method to the output of variable

I am working on Azure Function (Http Trigger), and came across with this task.
I am trying to display the output of method (ListVendors.Run(logger)) into inside variable (responseMessage) so that the values would be carried into Http post.
public static class Function1
{
[FunctionName("HttpTrigger_1111_1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
///Calling from other method starts:
ILogger logger = Bootstrap.Logger("Program");
ListVendors.Run(logger);
///Calling from other method ends:
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
string responseMessage = string.IsNullOrEmpty(name)
? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
: $"Hello, {name}. This HTTP triggered function executed successfully.";
return new OkObjectResult(responseMessage);
}
}
Basically, I am trying to insert the output of:
ListVendors.Run(logger);
Inside "responseMessage".
return new OkObjectResult(responseMessage);
How do I modify the code to do that?
Bottom is code for ListVendors:
public static class ListVendors
{
public static void Run(ILogger logger)
{
OnlineClient client = Bootstrap.Client(logger);
ReadByQuery query = new ReadByQuery()
{
ObjectName = "VENDOR",
PageSize = 2, // Keep the count to just 2 for the example
Fields =
{
"RECORDNO",
"VENDORID",
}
};
logger.LogInformation("Executing query to Intacct API");
Task<OnlineResponse> task = client.Execute(query);
task.Wait();
OnlineResponse response = task.Result;
Result result = response.Results[0];
try
{
dynamic json = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(result.Data));
string jsonString = json.ToString();
logger.LogDebug(
"Query successful - page 1 [ Total count={0}, Data={1} ]",
result.TotalCount,
jsonString
);
Console.WriteLine("Page 1 success! Number of vendor objects found: " + result.TotalCount + ". Number remaining: " + result.NumRemaining);
} catch (NullReferenceException e)
{
logger.LogDebug("No response in Data. {0}", e);
}
LogManager.Flush();
int i = 1;
while (result.NumRemaining > 0 && i <= 3 && !string.IsNullOrEmpty(result.ResultId))
{
i++;
ReadMore more = new ReadMore()
{
ResultId = result.ResultId
};
Task<OnlineResponse> taskMore = client.Execute(more);
taskMore.Wait();
OnlineResponse responseMore = taskMore.Result;
Result resultMore = responseMore.Results[0];
try
{
dynamic resultMoreJson =
JsonConvert.DeserializeObject(JsonConvert.SerializeObject(resultMore.Data));
string resultMoreJsonString = resultMoreJson.ToString();
logger.LogDebug(
"Read More successful - page " + i + " [ Total remaining={0}, Data={1} ]",
resultMore.NumRemaining,
resultMoreJsonString
);
Console.WriteLine("Page " + i + " success! Records remaining: " + resultMore.NumRemaining);
}
catch (NullReferenceException e)
{
logger.LogDebug("No response in Data. {0}", e);
}
finally
{
LogManager.Flush();
}
}
Console.WriteLine("Successfully read " + i + " pages");
}
}
}

Connection reset issue in .net core api call (net::ERR_CONNECTION_RESET 200 (OK))

I have a .net core API service which is called from a angular client project.
When a user request a status of his payment, we will make call to this service api and this service will then call a payment gateway service to fetch the status of payment and the output result will return to the user.
When i try to integrate this i am facing this below error.
net::ERR_CONNECTION_RESET 200 (OK)
core.js:5967 ERROR Unknown Error
This above issue is not showing when i try to hit the service after putting one breakpoint. Its also returning the result.
This is how entire flow works
Client side call performs by user
this.dataservice.postFeed(method, JSON.stringify(this.initsearch)).subscribe(result => {
var response = result.body["data"];
console.log(response);
});
Server side code looks like
[HttpPost]
public async Task<IActionResult> Post([FromBody] ObjectModel searchValue)
{
ApiResponse<string> response = new ApiResponse<string>();
IBaseResult<string> result = await _adlerBo.GetPaymentStatus(searchValue);
response.Success = result.success;
response.Data = result.Data;
return Ok(response);
}
In BusinessObject.cs
public async Task<IBaseResult<string>> GetPaymentStatus(PaymentSearchModel requestModel){
string apiResponse = await PaymentStatusCheckUsingAPI(requestModel.orderid);
return apiResponse ;
}
private async Task<string> PaymentStatusCheckUsingAPI(string orderNumber)
{
string message = await PostPaymentRequestToGateway(statusApiUrl, authQueryUrlParam);
NameValueCollection param = await GetResponseMap(message);
string status = "";
string encResJson = "";
if (param != null && param.Count == 2)
{
for (int i = 0; i < param.Count; i++)
{
if ("status".Equals(param.Keys[i]))
{
status = param[i];
}
if ("enc_response".Equals(param.Keys[i]))
{
encResJson = param[i];
}
}
if (!"".Equals(status) && status.Equals("0"))
{
resJson = crypto.Decrypt(encResJson, workingKey);
}
else if (!"".Equals(status) && status.Equals("1"))
{
Console.WriteLine("failure response: " + encResJson);
}
}
return resJson;
}
private async Task<string> PostPaymentRequestToGateway(string queryUrl, string urlParam)
{
string message = "";
try
{
StreamWriter myWriter = null;// it will open a http connection with provided url
WebRequest objRequest = WebRequest.Create(queryUrl);//send data using objxmlhttp object
objRequest.Method = "POST";
//objRequest.ContentLength = TranRequest.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";//to set content type
myWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
myWriter.Write(urlParam);//send data
myWriter.Close();//closed the myWriter object
// Getting Response
System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();//receive the responce from objxmlhttp object
using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
{
message = await sr.ReadToEndAsync();
//Response.Write(message);
}
}
catch (Exception exception)
{
Console.Write("Exception occured while connection." + exception);
}
return message;
}
private async Task<NameValueCollection> GetResponseMap(string message)
{
//await Task.Delay(2000); I did this with no Luck
NameValueCollection Params = new NameValueCollection();
if (message != null || !"".Equals(message))
{
string[] segments = message.Split('&');
foreach (string seg in segments)
{
string[] parts = seg.Split('=');
if (parts.Length > 0)
{
string Key = parts[0].Trim();
string Value = parts[1].Trim();
Params.Add(Key, Value);
}
}
}
return await Task.FromResult(Params);
}
Any idea how to fix this? Why its working when i put breakpoint and not otherwise.
Am i doing correct asynchronous implimentsion in my api?

HttpClient.SendAsync is throwing "A task was canceled" issue

We are making a PUT call to the service layer to update an entity information
HttpClient.SendAsync method is throwing "A task was canceled" issue even though the API call is successfully made to the backend service layer. I could see the logs from service layer.
Initially I thought it could be related to timeout, so I increased the timeout from 10 seconds to 30 seconds, still the program is waiting for 30 seconds and gets timed out with the error "A task was canceled". But the api call was successfully completed in Service Layer within even 5 seconds
Please find below my code
protected override void Execute(CodeActivityContext context)
{
string uuid = UUID.Get(context);
Console.WriteLine(uuid + ": Http Api Call - STARTED");
string endPoint = EndPoint.Get(context);
string contentType = ContentType.Get(context);
string acceptFormat = AcceptFormat.Get(context);
HttpMethod httpMethod = HttpApiMethod.Get(context);
string clientCertificatePath = ClientCertificatePath.Get(context);
string clientCertificatePassword = ClientCertificatePassword.Get(context);
double httpTimeOut = HttpTimeout.Get(context);
Dictionary<string, string> requestHeaders = RequestHeaders.Get(context);
Dictionary<string, string> pathParams = PathParams.Get(context);
Dictionary<string, string> queryParams = QueryParams.Get(context);
string requestBody = RequestBody.Get(context);
WebRequestHandler webRequestHandler = new WebRequestHandler();
webRequestHandler.MaxConnectionsPerServer = 1;
if (clientCertificatePath != null && clientCertificatePath.Trim().Length > 0)
{
X509Certificate2 x509Certificate2 = null;
if (clientCertificatePassword != null && clientCertificatePassword.Trim().Length > 0)
{
x509Certificate2 = new X509Certificate2(clientCertificatePath.Trim(),
clientCertificatePassword.Trim());
}
else
{
x509Certificate2 = new X509Certificate2(clientCertificatePath.Trim());
}
webRequestHandler.ClientCertificates.Add(x509Certificate2);
}
HttpClient httpClient = new HttpClient(webRequestHandler)
{
Timeout = TimeSpan.FromMilliseconds(httpTimeOut)
};
if (acceptFormat != null)
{
httpClient.DefaultRequestHeaders.Add("Accept", acceptFormat);
}
HttpResponseMessage httpResponseMessage = InvokeApiSync(httpClient, endPoint,
httpMethod, contentType,
requestHeaders, pathParams,
queryParams, requestBody,
uuid
);
HttpResponseMessageObject.Set(context, httpResponseMessage);
ResponseBody.Set(context, httpResponseMessage.Content.ReadAsStringAsync().Result);
StatusCode.Set(context, (int)httpResponseMessage.StatusCode);
Console.WriteLine(uuid + ": Http Api Call - ENDED");
}
private HttpResponseMessage InvokeApiSync(HttpClient httpClient,
string endPoint,
HttpMethod httpMethod,
string contentType,
Dictionary<string, string> requestHeaders,
Dictionary<string, string> pathParams,
Dictionary<string, string> queryParams,
string requestBody,
string uuid)
{
if (pathParams != null)
{
ICollection<string> keys = pathParams.Keys;
if (keys.Count > 0)
{
foreach (string key in keys)
{
endPoint = endPoint.Replace(":" + key, pathParams[key]);
}
}
}
if (queryParams != null)
{
List<string> keys = new List<string>(queryParams.Keys);
if (keys.Count > 0)
{
endPoint = string.Concat(endPoint, "?", keys[0], "=", queryParams[keys[0]]);
for (int index = 1; index < keys.Count; index++)
{
endPoint = string.Concat(endPoint, "&", keys[index], "=", queryParams[keys[index]]);
}
}
}
try
{
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(httpMethod, endPoint);
if (requestHeaders != null)
{
foreach (string key in requestHeaders.Keys)
{
httpRequestMessage.Headers.Add(key, requestHeaders[key]);
}
}
if (httpMethod.Equals(HttpMethod.Put) || httpMethod.Equals(HttpMethod.Post))
{
StringContent reqContent = null;
if (requestBody != null)
{
reqContent = new StringContent(requestBody);
}
else
{
reqContent = new StringContent("");
}
reqContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
httpRequestMessage.Content = reqContent;
}
HttpResponseMessage httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result;
return httpResponseMessage;
}
catch (Exception exception)
{
Console.WriteLine(uuid + " : HttpApi Error Has Occurred");
Console.WriteLine(uuid + " : " + exception.Message);
Console.WriteLine(uuid + " : " + exception.StackTrace);
throw exception;
}
}
Any help would be much appreciated. Thanks.!

Posting multipart request containing jpg and json causes interal server error and win32 status 64 on IIS

My winforms app sends PUT/POST requests to asp.net web api service. Mostly it sends json object as request's content and those request work well. Sometimes, when it needs to send jpg along with json object, so it creates multiPart request where jpg is content and json is passed in url, like so:
example.com/EditPart?id=193&PartJson=<serialized json object>
Here's full definition of the method sending the request:
public async void Edit(string attachmentPath)
{
using (var client = new HttpClient())
{
var serializedProduct = JsonConvert.SerializeObject(this, new JsonSerializerSettings { DateFormatString = "yyyy-MM-ddTHH:mm:ss.fff" });
string url = Secrets.ApiAddress + $"Edit{typeof(T).Name}?token=" + Secrets.TenantToken + $"&id={this.Id}&UserId={RuntimeSettings.UserId}" + $"&{typeof(T).Name}Json={serializedProduct}";
MultipartFormDataContent content = new MultipartFormDataContent();
try
{
using (var fileStream = System.IO.File.OpenRead(attachmentPath))
{
var fileInfo = new FileInfo(attachmentPath);
StreamContent fcontent = new StreamContent(fileStream);
fcontent.Headers.Add("Content-Type", "application/octet-stream");
fcontent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + fileInfo.Name + "\"");
content.Add(fcontent, "file", fileInfo.Name);
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
var result = await client.PutAsync(url, content);//<--stops here
if (result.IsSuccessStatusCode)
{
MessageBox.Show("Edycja zakończona powodzeniem!");
}
else
{
MessageBox.Show("Serwer zwrócił błąd przy próbie edycji. Wiadomość: " + result.ReasonPhrase);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Problem z wysyłką żądania do serwera. Wiadomość: " + ex.Message + ". " + ex.InnerException.Message, "Błąd żądania", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
It goes to await client.PutAsync(url, content); and then straight to exception saying: An error occurred while sending the request. The underlaying connection was closed. An unexpected error occurred on receive.
When I check in IIS logs, I see the request gets properly to the server, but ends with status 500 and win32 status 64.. I even put logging with NLog to EditPart method, but it never fires.. It looks like the method isn't called at all, but of course from IIS logs I know it is.
Here's complete EditPart definition on asp.net web api:
[HttpPut]
[Route("EditPart")]
[ResponseType(typeof(void))]
public HttpResponseMessage EditPart(string token, int id, int UserId, string PartJson)
{
try
{
JavaScriptSerializer jss = new JavaScriptSerializer();
JDE_Parts item = jss.Deserialize<JDE_Parts>(PartJson);
try
{
var items = db.JDE_Parts.Where(u => u.PartId == id);
if (items.Any())
{
Logger.Info("EditPart: Znalazłem odpowiednią część. Przystępuję do edycji Id={id}, UserId={UserId}", id, UserId);
JDE_Parts orgItem = items.FirstOrDefault();
//handle image
var httpRequest = HttpContext.Current.Request;
if (httpRequest.ContentLength > 0)
{
//there's a new content
if (httpRequest.ContentLength > Static.RuntimeSettings.MaxFileContentLength)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, $"{item.Name} przekracza dopuszczalną wielość pliku ({Static.RuntimeSettings.MaxFileContentLength} MB) i został odrzucony");
}
var postedFile = httpRequest.Files[0];
string filePath = "";
if (postedFile != null && postedFile.ContentLength > 0)
{
Logger.Info("EditPart: Znaleziono nowe pliki. Przystępuję do zapisu na dysku. Id={id}, UserId={UserId}", id, UserId);
var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
filePath = $"{Static.RuntimeSettings.Path2Files}{item.Token + ext.ToLower()}";
string oFileName = db.JDE_Parts.Where(p => p.PartId == id).FirstOrDefault().Image;
if (!string.IsNullOrEmpty(oFileName))
{
// There was a file, must delete it first
Logger.Info("EditPart: Istnieją poprzednie pliki pod tą nazwą. Przystępuję do usuwania. Id={id}, UserId={UserId}", id, UserId);
System.IO.File.Delete(Path.Combine(RuntimeSettings.Path2Files, oFileName));
System.IO.File.Delete(Path.Combine(RuntimeSettings.Path2Thumbs, oFileName));
}
postedFile.SaveAs(filePath);
Logger.Info("EditPart: Zapisano pliki. Przystępuję do utworzenia miniatury.. Id={id}, UserId={UserId}", id, UserId);
Static.Utilities.ProduceThumbnail(filePath);
item.Image = item.Token + ext.ToLower();
}
}
try
{
Logger.Info("EditPart: Przystępuję do zapisu zmian w bazie danych. Id={id}, UserId={UserId}", id, UserId);
db.Entry(orgItem).CurrentValues.SetValues(item);
db.Entry(orgItem).State = EntityState.Modified;
db.SaveChanges();
Logger.Info("EditPart: Zapisano zmiany w bazie. Id={id}, UserId={UserId}", id, UserId);
}
catch (Exception ex)
{
Logger.Error("Błąd w EditPart. Id={id}, UserId={UserId}. Szczegóły: {Message}, nowa wartość: {item}", id, UserId, ex.ToString(), item);
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
}
catch (Exception ex)
{
Logger.Error("Błąd w EditPart. Id={id}, UserId={UserId}. Szczegóły: {Message}, nowa wartość: {item}", id, UserId, ex.ToString(), item);
return Request.CreateResponse(HttpStatusCode.NoContent);
}
}
catch (Exception ex)
{
Logger.Error("Błąd w EditPart. Id={id}, UserId={UserId}. Szczegóły: {Message}", id, UserId, ex.ToString());
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
}
return Request.CreateResponse(HttpStatusCode.NoContent);
}
What's weird is that all this worked perfectly well for months, until some time ago it stopped.. Also, when I debug the asp.net application on my machine, the request runs without any problem.. What else I can do to trace this issue?
When you debug the asp.net api application, it can run without any problem. This shows that there is no problem with the api application.
But the status in IIS logs is 500, errors greater than 500 are generally caused by the server, the client is normal. This contradicts the above conclusion that the api is no problem.
Since I don’t know the version of .net you are using, I’m not sure whether to use TLS 1.0, 1.1 or 1.2. Different versions of .net target different TLS, the latest 4.6 currently supports 1.2. So the most safe and effective way is to set all TLS and SSL.
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12| SecurityProtocolType.Ssl3;
It turned out that the problem was single line in my Edit method in the client app. After changing fcontent.Headers.Add("Content-Type", "application/octet-stream") to fcontent.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(fileInfo.Name)) it works flawlessly. In other words, my request wasn't even sent to the server. What's puzzling, though, is the fact that the same code had been working for months and then stopped..
public async void Edit(string attachmentPath)
{
using (var client = new HttpClient())
{
var serializedProduct = JsonConvert.SerializeObject(this, new JsonSerializerSettings { DateFormatString = "yyyy-MM-ddTHH:mm:ss.fff" });
string url = Secrets.ApiAddress + $"Edit{typeof(T).Name}?token=" + Secrets.TenantToken + $"&id={this.Id}&UserId={RuntimeSettings.UserId}" + $"&{typeof(T).Name}Json={serializedProduct}";
MultipartFormDataContent content = new MultipartFormDataContent();
try
{
using (var fileStream = System.IO.File.OpenRead(attachmentPath))
{
var fileInfo = new FileInfo(attachmentPath);
StreamContent fcontent = new StreamContent(fileStream);
fcontent.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(fileInfo.Name)); //fcontent.Headers.Add("Content-Type", "application/octet-stream");
fcontent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + fileInfo.Name + "\"");
content.Add(fcontent, "file", fileInfo.Name);
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
var result = await client.PutAsync(url, content);//<--stops here
if (result.IsSuccessStatusCode)
{
MessageBox.Show("Edycja zakończona powodzeniem!");
}
else
{
MessageBox.Show("Serwer zwrócił błąd przy próbie edycji. Wiadomość: " + result.ReasonPhrase);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Problem z wysyłką żądania do serwera. Wiadomość: " + ex.Message + ". " + ex.InnerException.Message, "Błąd żądania", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

Passing JSON string list malforms strings?

I'm saving a list of strings to my backend api but its malforming the string somehow. I have checked all possible things but I have had no sleep for 48 hours so I'm probably missing it.
It seems to replace _ with amp - not sure.
Correct string (also the string before persisting)
&_nc_cat=100&oh=2709db2b099e5eb5bb6eb19654de828a&oe=5E7FF7C5
The string after persisting
&_nc_cat=100&oh=2cda55a0255b0ef3afabe535412a43f8&oe=5E7FF7C5
The full orignal correct string is actually
https://scontent-lhr3-1.cdninstagram.com/s640x640/75448871_111514890143520_4913259559873269659_n.jpg?_nc_ht=scontent-lhr3-1.cdninstagram.com&_nc_cat=100&oh=2709db2b099e5eb5bb6eb19654de828a&oe=5E7FF7C5
Here is how I save to my api
var response = HttpFactory.PushItemToCache(new Dictionary<string, object>
{
{ "item", Url },
{ "username", Username },
{ "name", Name },
{ "picture", Picture },
{ "pictures", Pictures },
});
Http Methods:
public static IRestResponse PushItemToCache(Dictionary<string, object> data)
{
return HttpUtilities.Post("/api/cache", data);
}
Post method:
public static IRestResponse PerformResource(string resource, IDictionary<string, object> data = default, string method = "GET", bool checkToken = true)
{
var sw = Stopwatch.StartNew();
var request = new RestRequest(resource);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", $"Bearer {_bearerToken}");
if (data == null)
{
data = new Dictionary<string, object>();
}
data.Add("owner", Environment.UserName + Environment.MachineName);
if (method != "GET")
{
request.AddJsonBody(data);
}
else
{
foreach (var pair in data)
{
request.AddParameter(pair.Key, pair.Value);
}
}
IRestResponse response;
switch (method)
{
case "POST":
response = RestClient.Post(request);
break;
case "DELETE":
response = RestClient.Delete(request);
break;
case "PUT":
response = RestClient.Delete(request);
break;
case "PATCH":
response = RestClient.Patch(request);
break;
default:
response = RestClient.Get(request);
break;
}
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.NotFound)
{
new ConsoleLogger().Error("Response for " + resource + " returned " + response.StatusDescription);
new ConsoleLogger().Error(response.Content);
new ConsoleLogger().Error(response.ErrorMessage);
}
if (sw.Elapsed.TotalSeconds >= 5)
{
new ConsoleLogger().Pink($"This request ({resource}) took {sw.Elapsed.TotalSeconds} seconds");
}
return response;
}
Looks like your string is url encoded, you can convert it back using HttpUtility.UrlDecode
working example here

Categories