I have a following curl request
curl -X POST -D- --insecure -H "ApiKey: $api_key" https://api.myapi.com/service/12345/purge/12345--resolve [http://api.myapi.com:443:11.112.121.194/]api.myapi.com:443:11.112.121.194
I want to convert that over to HttpClient.
var baseUrl = "https://api.myapi.com";
HttpClient httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) };
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Add("ApiKey", "api_key");
var request = new HttpRequestMessage(HttpMethod.Post, $"service/{12345}/purge/{12345}");
request.Content = new StringContent(null, Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request);
How do I add --resolve parameter to HttpRequest?
Related
Imagine you are making a HTTP request for example (though it could be any http call):
string baseurl = LocalConfigKey.BaseUrl;
string geturl = string.Format("{0}leo-platform-api/api/v1/Orchestrator/Endpoint", baseurl);
var response = string.Empty;
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", LocalConfigKey.APIMSubscriptionKey);
HttpResponseMessage result = httpClient.GetAsync(geturl).GetAwaiter().GetResult();
result.EnsureSuccessStatusCode();
if (result.IsSuccessStatusCode)
{
response = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
}
Is it possible to generate curl out of this request that can be logged in a db etc ?
You can use this package to convert HTTPClient to curl:
First install NuGet package:
dotnet add package HttpClientToCurl
Example:
Declare request requirements:
string requestBody = #"{ ""name"" : ""amin"",""requestId"" : ""10001000"",""amount"":10000 }";
string requestUri = "api/test";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri);
httpRequestMessage.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
using var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("http://localhost:1213");
Get curl from request
httpClient.GenerateCurlInConsole(httpRequestMessage, requestUri ); // Generate curl in console
httpClient.GenerateCurlInFile(httpRequestMessage, requestUri ); // Generate curl in file
HTTP call
// Call PostAsync => await client.PostAsync(requestUri, httpRequest.Content);
To get more information see the repo GitHub docs
There has been a lot of similar questioning on this one but I could not get any answers working for me..
I am calling another api Post request from my controller..but I get a 400 bad request all the time..
public async Task<JsonResult> TestSCIMPost(AppAuth auth)
{
//Method 3:
HttpClient client = new HttpClient();
var jsonRequest = Newtonsoft.Json.JsonConvert.SerializeObject(auth);
var content = new StringContent(jsonRequest);
content.Headers.Remove("Content-Type");
content.Headers.Add("Content-Type", "application/json");
HttpResponseMessage response = await client.PostAsJsonAsync(
URL, content);
return new JsonResult(response);
}
curl
curl -X POST "https://localhost:5001/api/Employee/api/Employee/TestSCIMPost" -H "accept: /" -H "Content-Type: application/json-patch+json" -d "{"client_id":"xyz","grant_type":"cc","client_secret":"abc","scope":"read"}"
I have tried a couple of other ways that I am listing below..
public async Task<JsonResult> TestSCIMPost(AppAuth auth)
{
/*var response = string.Empty;
var jsonRequest = Newtonsoft.Json.JsonConvert.SerializeObject(auth);
byte[] messageBytes = System.Text.Encoding.UTF8.GetBytes(jsonRequest);
var content = new ByteArrayContent(messageBytes);
//HttpContent c = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
content.Headers.Remove("Content-Type");
content.Headers.Add("Content-Type", "application/json");
//content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
using (var client = new HttpClient())
{
//client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage result = await client.PostAsync(URL, content);
if (result.IsSuccessStatusCode)
{
response = result.StatusCode.ToString();
}
}*/
//Method:2
//HttpClient client = new HttpClient();
//client.BaseAddress = new Uri(URL);
//client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
//var requestMessage = Newtonsoft.Json.JsonConvert.SerializeObject(auth);
//var content = new StringContent(requestMessage, Encoding.UTF8, "application/json");
//content.Headers.Remove("Content-Type");
//content.Headers.Add("Content-Type", "application/json");
//HttpResponseMessage result = await client.PostAsync(URL, content);
return new JsonResult(response);
}
The body is coming from auth (frontend that i am serializing and adding in my request)
What's going wrong here? Is it utf-encoding? how to fix?
One reason this can happen is if you are posting content in the body (as you are doing) where the parser expects to find it in the query.
So if you have something like this:
string url = "https://localhost:5001/api/Employee/TestSCIMPost";
var content = new StringContent("{\"client_id\":\"xyz\",\"grant_type\":\"cc\"}");
HttpResponseMessage response = await client.PostAsync(url, content);
Try changing it to this:
string url = "https://localhost:5001/api/Employee/TestSCIMPost?client_id=xyz&grant_type=cc";
var content = new StringContent("");
HttpResponseMessage response = await client.PostAsync(url, content);
I am struggeling to convert a curl command to functioning c# code.
curl "https://MY_SERVER/api/3.4/sites/site-id/workbooks" -X POST -H "X-Tableau-Auth:credentials token" -H "Content-Type: multipart/mixed;" -F "request_payload=#publish-workbook.xml" -F "tableau_workbook=#MY_WORKBOOK.twbx"
Can anyone help?
Using curl to C# convertor I've got this result:
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://my_server/api/3.4/sites/site-id/workbooks"))
{
request.Headers.TryAddWithoutValidation("X-Tableau-Auth", "credentials token");
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new ByteArrayContent(File.ReadAllBytes("publish-workbook.xml")),
"request_payload", Path.GetFileName("publish-workbook.xml"));
multipartContent.Add(new ByteArrayContent(File.ReadAllBytes("MY_WORKBOOK.twbx")),
"tableau_workbook", Path.GetFileName("MY_WORKBOOK.twbx"));
request.Content = multipartContent;
var response = await httpClient.SendAsync(request);
}
}
In "Path.GetFileName()" you should change the file path.
use some online converter or make custom one. its on you.
C# of your curl below:
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://my_server/api/3.4/sites/site-id/workbooks"))
{
request.Headers.TryAddWithoutValidation("X-Tableau-Auth", "credentials token");
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new ByteArrayContent(File.ReadAllBytes("publish-workbook.xml")), "request_payload", Path.GetFileName("publish-workbook.xml"));
multipartContent.Add(new ByteArrayContent(File.ReadAllBytes("MY_WORKBOOK.twbx")), "tableau_workbook", Path.GetFileName("MY_WORKBOOK.twbx"));
request.Content = multipartContent;
var response = await httpClient.SendAsync(request);
}
}
I have Httpclient functions that I am trying to convert to RestSharp but I am facing a problem I can't solve with using google.
client.BaseAddress = new Uri("http://place.holder.nl/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",access_token);
HttpResponseMessage response = await client.GetAsync("api/personeel/myID");
string resultJson = response.Content.ReadAsStringAsync().Result;
This Code is in my HttpClient code, which works good, but I can't get it to work in RestSharp, I always get Unauthorized when using RestSharp like this:
RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest();
client.Authenticator = new HttpBasicAuthenticator("Bearer", access_token);
request.AddHeader("Accept", "application/json");
request.Resource = "api/personeel/myID";
request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
Am I missing something with authenticating?
This has fixed my problem:
RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest("api/personeel/myID", Method.GET);
request.AddParameter("Authorization",
string.Format("Bearer " + access_token),
ParameterType.HttpHeader);
var response = client.Execute(request);
Upon sniffing with Fiddler, i came to the conclusion that RestSharp sends the access_token as Basic, so with a plain Parameter instead of a HttpBasicAuthenticator i could force the token with a Bearer prefix
Try this
RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest("api/personeel/myID",Method.Get);
request.AddParameter("Authorization",$"Bearer {access_token}",ParameterType.HttpHeader);
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
If anyone happens on this, it looks like as of V 106.6.10 you can simply add default parameters to the client to save yourself from having to add your Auth token to every request method:
private void InitializeClient()
{
_client = new RestClient(BASE_URL);
_client.DefaultParameters.Add(new Parameter("Authorization",
string.Format("Bearer " + TOKEN),
ParameterType.HttpHeader));
}
When the method is called, it returns Status code: not found. I'm sure that the uri is correct, so i think that the problem is the content. This is the api called by terminal:
curl --request POST 'https://api.uniparthenope.it/user/radius/auth' --data "user=xxxxxxxxxx" --data "passw=xxxxxxxxxx"
and this is my code:
public async Task<string> Login()
{
client = new HttpClient();
client.BaseAddress = new Uri("https://api.uniparthenope.it");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.MaxResponseContentBufferSize = 256000;
content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("user",Username),
new KeyValuePair<string,string>("passw",Password)
});
content.Headers.ContentType.CharSet = "UTF-8";
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await client.PostAsync("user/radius/auth", content);
//return response.RequestMessage.ToString();
return response.StatusCode.ToString();
}