ASP.NET Equivalent to this cURL command - c#

I'm working with the Twilio API and it provides examples in PHP and Ruby. I'm working on a site to send text messages through the API that's coded in ASP.NET MVC 3, and using my limited knowledge of the WebRequest object, I was able to translate this:
curl -X POST 'https://api.twilio.com/2010-04-01/Accounts/AC4840da0d7************f98b20b084/SMS/Messages.xml' \
-d 'From=%2B14155992671' \
-u AC4840da0d7************f98b20b084:f7fc2**************75342
Into this:
var request =
WebRequest.Create(MessageApiString + "?From=+14*********1&To=" + Phone + "&Body=" + smsCampaign.Message);
var user = "AC4840da0d7************f98b20b084";
var pass = "f7fc2**************75342";
string credentials = String.Format("{0}:{1}", user, pass);
request.Headers.Add("Authorization", credentials);
var result = request.GetResponse();
But it's not authenticating, I'm getting a 401 from their API. What is the equivalent C# to the cURL -u command?
Update
var request =
WebRequest.Create(MessageApiString + "?From=+14155992671&To=" + Phone + "&Body=" + smsCampaign.Message);
var cc = new CredentialCache();
cc.Add(new Uri(MessageApiString), "NTLM", new NetworkCredential("AC4840da0d7************f98b20b084", "f7fc2**************75342"));
request.Credentials = cc;
request.Method = "POST";
var result = request.GetResponse();
Still getting 401. Any ideas?
Update 2
Alright, thanks to the answers below I was able to get through to the api, but now I'm getting a 400 Bad Request. Is there a cleaner way to build a query string to pass this data along? The three fields are From, To, and Body.

Try including
request.Method = "POST";
and
request.Credentials = new NetworkCredential("username", "password");

The -u option in Curl is to specify a username and password for Server Authentication.
For C# this is set using the WebRequest.Credentials property.

Related

C# Oracle Rest API, Authentication Issue

I am trying to use Ocacle's Financial REST API and I'm having trouble making it work in C# in VS2019.
I can confirm the restful call works using Postman, so I know my credentials are fine but I must be missing something trying this with in code.
So URL is like so:
http://MYCLOUDDOMAIN/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail
So I stick that in postman, put in my credentials (basic auth) and it works find. In VS I've tried both the RestSharp way and basic HTTPRequest way as follows:
HttpWebRequest r = (HttpWebRequest)WebRequest.Create("/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger US,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail");
r.Method = "GET";
string auth = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("Username" + ":" + "Password"));
r.Headers.Add("Authorization", "Basic" + " " + auth);
r.ContentType = "application/vnd.oracle.adf.resourcecollection+json";
using (HttpWebResponse resp = (HttpWebResponse)r.GetResponse())
{
int b = 0;
}
RestSharp:
var client = new RestClient("http://MYCLOUDDOMAIN/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger US,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail");
client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("UserName", "Password");
//Tried authorization this way as well.
//JObject AuthRequest = new JObject();
//AuthRequest.Add("Username", "UserName");
//AuthRequest.Add("Password", "Password");
var request = new RestRequest();
request.Method = Method.GET;
request.RequestFormat = DataFormat.Json;
//request.AddParameter("text/json", AuthRequest.ToString(), ParameterType.RequestBody);
request.AddHeader("Content-Type", "application/vnd.oracle.adf.resourcecollection+json");
request.AddHeader("REST-Framework-Version", "1");
var response = client.Get(request);
No matter what I try I am always 401 not authorized. I suspect its some kind of header thing? I can't see the raw request header in postman
I am new to REST. I am used to using WSDLs soap services.
Try this.
var handler = new HttpClientHandler
{
Credentials = new NetworkCredential("username", "password")
};
using (var client = new HttpClient(handler))
{
var result = await client.GetAsync("url");
}
Good luck!
I figured out what the problem was.
In postman, it was fine with the URL I posted being HTTP but in C# code it was not. I switched the URL to HTTPS and it started working just fine.

Converting CURL request to C# for accessing Snipcart API returns 401 Unauthorized

I am trying to access the Snipcart API (Reference - https://docs.snipcart.com/api-reference/authentication). I have created an API key and followed the steps mentioned in the documentation.
I am trying to Convert a CURL request to C#. I chose to use HttpWebRequest. I get 401 Unauthorized returned from the Server. I am not able to figure out what's wrong with my request.
Actual Curl Request: - curl -H "Accept: application/json"
https://app.snipcart.com/api/orders
-u {API_KEY}:
The following is the code that i tried converting the above curl request to
string baseURL = "https://app.snipcart.com/api/orders";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseURL);
req.AllowAutoRedirect = true;
req.ContentType = "application/json";
req.Accept = "application/json";
req.Method = "GET";
req.Headers.Add("API_Key", "MY_API_KEY_VALUE_COMES_HERE");
string jsonResponse = null;
using (WebResponse resp = req.GetResponse())
{
if (req.HaveResponse && resp != null)
{
using (var reader = new StreamReader(resp.GetResponseStream()))
{
jsonResponse = reader.ReadToEnd();
}
}
}
Console.Write(jsonResponse);
You need to send the header as a basic auth header instead of "API_Key" Try something like this.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseURL);
req.AllowAutoRedirect = true;
req.ContentType = "application/json";
req.Accept = "application/json";
req.Method = "GET";
var basicAuthHeader = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("MY_API_KEY_VALUE_COMES_HERE"));
req.Headers.Add("Authorization", "Basic " + basicAuthHeader);
The API reference from Snipcart says you need Basic HTTP Authentication.
When I have a look at your code, I think you should change this line
req.Headers.Add("API_Key", "MY_API_KEY_VALUE_COMES_HERE");
to
req.Credentials = new NetworkCredential("API_Key", "MY_API_KEY_VALUE_COMES_HERE");
A kind of the same issue is described in this topic, you can take it as reference.
If it's not solving the issue, you could have a closer look at the curl API parameters manual, and then translate it to C# code.
curl -H "Accept: application/json" \
https://app.snipcart.com/api/orders \
-u {API_KEY}:

How to pass API_KEY through HttpWebRequest

I'm trying to send curl request passing some headers and authentication info.
All information i want to send went successfully but I'm stuck with how to send the api key that should be used instead of the normal username/password manner.
when I use online curl websites to send the curl request, I put : after the api key and then everything works perfectly.
And this is what i want to do in C# using HttpWebRequest
This is the code I'm using in order to do that:
string credentials = String.Format("{0}:{1}", "API_KEY", "GivenApiKey: ");
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("Basic ", base64);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.website.com/test");
httpWebRequest.ReadWriteTimeout = 100000;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.UserAgent = "GivenUserAgent";
httpWebRequest.Credentials = new NetworkCredential("Authorization", authorization);
please any help?
You should put the Authorization in a Header so:
httpWebRequest.Headers["Authorization"] = "Bearer " + apikey;
Depending on the server you are contacting, you'll have to determine the input. In my case Bearer should be placed before the apikey.
As most servers use the following setup for authorization:
Authorization: <type> <credentials>

REST C# Get List Items

I am completely new to REST API.
I would like to retrieve ListItems in xml format from an external site in C#.
I have got the username and password for the site (which uses Mixed authentication by the way).
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create("https://<site>/_api/web/lists");
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/atom+xml";
//endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
endpointRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("<domain>\\<username>:<password>"));
HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
I am using this piece of code that I found on MSDN.
Would anybody please be kind enough to tell me how do I get an access token?
Why am I getting 403 Forbidden error?
I think you can better use the NetworkCredential class:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
NetworkCredential credentials = new NetworkCredential("testuser", "testpass");
request.Credentials = credentials;
No need to send the Authorization header
When I have to use REST API I use Tiny.RestClient 1
In your case you have to write the call like that :
var client = new TinyRestClient(new HttpClient(), "https://<site>/_api/");
client.GetRequest("web/lists")
Hopes that help.
WithBasicAuthentication("username", "password").
ExecuteAsync();

Making HTTP Post with authorization in C#

I'm trying to Make your first call Paypal where the post message are in curl. I want to convert them to C#. But I can't edit Accept header.
curl https://api.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-H "Accept-Language: en_US" \
-u "EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp:EClusMEUk8e9ihI7ZdVLF5cZ6y0SFdVsY9183IvxFyZp" \
-d "grant_type=client_credentials"
My code is
string url = "https://api.sandbox.paypal.com/v1/oauth2/token";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//request.ContentType = "Content-type: text/xml";
//Client.Headers.Add(HttpRequestHeader.UserAgent, "user agent to send");
//request.Headers.Add(HttpRequestHeader.Accept, "application/json");
//request.Headers.Add(HttpRequestHeader.Referer, "string");
//request.Headers.Add(HttpRequestHeader.AcceptLanguage, "string");
request.Method = "POST";
string authInfo = "AfKNLhCngYfGb-Eyv5gn0MnzCDBHD7T9OD7PATaJWQzP3I1xDRV1mMK1i3WO:ECSAgxAiBE00pq-SY9YB5tHw0fd2UlayHGfMr5fjAaULMD2NFP1syLY7GCzt";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
//request.Headers["Accept"] = "application/json";
request.Headers["Accept-Language"] = "en_US";
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("grant_type=client_credentials");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
I'm getting internal server error 500. But it works fine with curl. How can I do this in C#?
One method I have used before to supply named values like this is to use the UploadValues method of a WebClient. This perfectly replicates the functionality you find in curl (I have used this for integration with the Instagram API for the same purpose).
Here is a little sample code to illustrate:
string authInfo = "AfKNLhCngYfGb-Eyv5gn0MnzCDBHD7T9OD7PATaJWQzP3I1xDRV1mMK1i3WO:ECSAgxAiBE00pq-SY9YB5tHw0fd2UlayHGfMr5fjAaULMD2NFP1syLY7GCzt";
WebClient client = new WebClient();
NameValueCollection values;
values = new NameValueCollection();
values.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo)));
values.Add("Accept", "application/json");
values.Add("Accept-Language", "en_US");
client.UploadValues("https://api.sandbox.paypal.com/v1/oauth2/token", values);
This may not work out of the box (as I have laid it out above) but will hopefully take you in the right direction.

Categories