The format for this particular request that works using CURL is:
--request POST --header "PRIVATE-TOKEN: xlxlxlxlxlxlxl" \
--form "file=#myfile.pdf" \
"https://company.com/api/v2/sendfile"
I can't figure out how to make the same request using Flurl.
What I've tried in Flurl is:
var response = await "https://company.com/api/v2"
.WithHeader("PRIVATE-TOKEN","xlxlxlxlxlxlxl")
.WithHeader("--form", "file=myfile.pdf")
.AppendPathSegment("sendFile")
.PostAsync();
I've also tried to use:
var response = await "https://company.com/api/v2/sendFile"
.PostMultipartAsync(mp => mp
.AddString("PRIVATE-TOKEN","xlxlxlxlxlxlxl")
.AddString("--form","file=myfile.pdf")
I have something wrong, but I'm unsure of what to try next.
Related
I trying implement Auth0 authentication/authorization in web api. But get 403 error code (No such host is known. (https:443))
Simple code for get token is below
var client = new AuthenticationApiClient(new Uri($"https://{ _config.GetValue<string>("auth0:Authority")}"));
var authenticationResponse = await client.GetTokenAsync(new RefreshTokenRequest
{
Audience = "https://dev-rignosgw.us.auth0.com/api/v2/",
ClientSecret = _config.GetValue<string>("auth0:ClientSecret"),
ClientId = _config.GetValue<string>("auth0:ClientId")
});
But if execute analogous query in postman it is work correctly and i get auth token in response. Query is below
curl --request POST \ --url
'https://dev-rignosgw.us.auth0.com/oauth/token' \ --header
'content-type: application/x-www-form-urlencoded' \ --data
grant_type=client_credentials \ --data client_id=CLIENT_ID \
--data client_secret=CLIENT_SECRET \ --data audience=https://dev-rignosgw.us.auth0.com/api/v2/
Question is folowing. What url must using in AuthenticationApiClient constructor? As I understand in my case it must beeen ttps://dev-rignosgw.us.auth0.com/oauth/token. Or I'm wrong?
I have never used Auth0 before. What i'm doing wrong? Thanks.
i try to work around converting this to c# but i cant understand the tags like -H others am familiar with like the BVN and secret key are clear to me, but i'm literally at cross road.
curl https://api.paystack.co/bank/resolve_bvn/:BVN
-H "Authorization: Bearer YOUR_SECRET_KEY"
-X GET
this enlightened me but i'm new to using curl
I only want to explain command flags.
-H means request header. In your case, you need to set header with name Authorization to the secret key Bearer YOUR_SECRET_KEY eg Bearer abcd123566 where abcd123566 is your secret key.
-X GET means your request method (HTTP verb) should be GET
-H means the headers of the request. In C# the code would look something like this:
private static HttpClient httpClient = new HttpClient();
var uri = new Uri("https://api.paystack.co/bank/resolve_bvn/:BVN");
var reqMessage = new HttpRequestMessage(HttpMethod.Get, uri);
reqMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_SECRET_KEY")
// Setting the request content (including content-type)
reqMessage.Content = new StringContent("Content of request", Encoding.UTF8, "application/json");
var resp = await httpClient.SendAsync(reqMessage);
You can read more HttpClient and API requests in C# here:
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netcore-3.1
https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client
I am writing a WPF application with C# that attempts to make an Google Cloud AutoML API call with HttpClient. I am able to make contact with the server but always get back an "Unauthorized" response. I have scoured StackOverflow and the AutoML documentation for any hint as to how to properly turn the "CURL" request into a simple HTTP request that I can execute programmatically within my C# application, but haven't found anything that gave enough guidance up to this point (hence my question).
Here is the CURL request that I am modeling my HTTP request after:
curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
https://automl.googleapis.com/v1beta1/projects/image-object-detection/locations/us-central1/models/MyProjectId:predict -d #request.json
There are elements of this request that I cannot figure out how to translate into C#, namely the Authorization: Bearer component. Do I need to somehow find a token and add it to a header or something? If so, how do I acquire this token in string form? That seems to be what I'm really stuck on.
And here is the C# code that I actually have up to this point.
public async Task<object> GetPrediction(string imagePath)
{
string apiKey = "MyApiKey";
string projectId = "MyProjectId";
HttpResponseMessage response;
byte[] img = File.ReadAllBytes(imagePath);
string jsonBody = "{\"payload\":{\"image\":{\"imageBytes\":\"" + Encoding.UTF8.GetString(imgBody) + "\"}}}";
string uri = $"https://automl.googleapis.com/v1beta1/projects/image-object-detection/locations/us-central1/models/{projectId}:predict?key={apiKey}";
string token = “MyToken”;
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Headers.TryAddWithoutValidation("Content-Type", "application/json");
request.Headers.Authorization = new AuthenticarionHeaderValue(“Bearer”, token);
request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
response = await client.SendAsync(request);
return Task.FromResult(response);
}
This code basically makes contact, then I get back a 401 "unauthorized" status code. Any suggestions or guidance would be greatly appreciated, and if additional information is required, I would be glad to post more. Thanks!
Update:
I modified the code block to include the suggested change from Nkosi, but I am still seeing the same 401 status code.
I am not seeing the Authorization header added to request
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)"
like in the cURL example
set the Authorization on the request before sending it
//...
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "{token-here}");
//...
I'm making a call to third-party api. Here's the third-party api info and what they expect:
POST /api/ HTTP/1.1
Host: testurl.com
Content-Type: multipart/form-data
curl https://testurl.com/api \
-H "Content-Type: multipart/form-data" \
-F "document[description]=meeting notes" \
-F "document[matter][id]=123" \
-F "document[document_category][name]=Offers" \
-F "document_version[last_modified_at]=2013-12-03T23:35:32+00:00" \
-F "document_version[uploaded_data]=#test.txt"
I need to write a c# equivalent post method to send these info. I have taken care of the header in the curl call, but I'm not sure on the rest of the form-data. For instance, the "document" and "document_version" along with their respective attributes (or whatever they are), how do I pass those info along?
Here's what I found: http://www.briangrinstead.com/blog/multipart-form-post-in-c
I did exactly what's done in that link, but got back Bad Request error. More specific error:
{"error":"api error","message":"undefined method `key?' for nil:NilClass"}
I have no idea what's going on in the third-api so I don't know what this error means. Also, I'm trying to post pdf doc.
You can use the HttpClient
var client = new HttpClient();
var image = File.ReadAllBytes("c:\\test.png");
var formData = new MultipartFormDataContent();
formData.Add(new StreamContent(new MemoryStream(image)), "name","fileName.png");
formData.Add(new StringContent("content"), "name");
var response = client.PostAsync("http://localhost:5001/api/someMethod", formData).Result;
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
Console.WriteLine(content);
}
This works good for me.
I am trying to write a program to authenticate to rackspace cloud files. The following command works with curl just fine:
curl -k -X POST https://identity.api.rackspacecloud.com/v2.0/tokens -d '{ "auth":{"RAX-KSKEY:apiKeyCredentials":{"username":"myusername","apiKey":"mykey"}}}' -H "Content-type: application/json"
However, I get a bad request (400) error with the following code:
var client = new RestClient("https://identity.api.rackspacecloud.com/v2.0");
var request = new RestRequest("tokens", Method.POST);
request.RequestFormat = DataFormat.Json;
string serText = "{ \"auth\":{\"RAX-KSKEY:apiKeyCredentials\"{\"username\":\"myusername\",\"apiKey\":\"mykey\"}}}";
request.AddBody(serText);
RestResponse response = (RestResponse)client.Execute(request);
Anybody have any ideas?
So, when adding my json body I need to do so as follows:
request.AddParameter("application/json", serText, ParameterType.RequestBody);
So basically, it was trying to serialize my already serialized json. I found this out by finding some other questions on stack overflow. I would point out this is not explained at all the official "documentation" for RestSharp.