About Basic Auth - c#

I'm trying to get some data from one api, this is mi code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using System.Text;
namespace DriverSenstarNMS
{
class Program
{
static void Main(string[] args)
{
using (var client = new HttpClient())
{
string url = "http://localhost/api/devices/";
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Authorization", "user:pass");
var response = client.GetAsync(url).Result;
var res = response.Content.ReadAsStringAsync().Result;
dynamic r = JObject.Parse(res);
Console.WriteLine(r);
}
}
}
}
currently I'm having:
Exception thrown: 'System.FormatException' in System.Net.Http.dll
An unhandled exception of type 'System.FormatException' occurred in System.Net.Http.dll
The format of value 'senstar:senstar' is invalid
The need to add basic auth, what's wrong?
Initially added the url, then added the authorization through the header, sent the request and then got the response

The format of the Authorization header for basic auth is
Authorization: Basic username:base64encode(password)

Related

automate the test case to validate the response “US” when the value for the input parameter “CurrencyCode” is “USD” Using C# RestSharp

I have developed a API using RapidAPI to get and automate test cases to validate response “US” when the value for the input parameter “CurrencyCode” is “USD” Using C# RestSharp.but it is fowing an error when its opening on .net console as below on get and IRestresponse.I need help to fix it.
here is my code.
using RestSharp;
using System;
using RestSharp.Authenticators;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IFSAPI
{
internal class Program
{
static void Main(string[] args)
{
//arrange
var client = new RestClient("https://wft-geo-db.p.rapidapi.com/v1/geo/countries?currencyCode=LKR");
var request = new RestRequest(Method.GET);
//
request.AddHeader("X-RapidAPI-Key", "2ade609583msh867a2c95e9e419dp1a1668jsnf1f880a47cc5");
request.AddHeader("X-RapidAPI-Host", "wft-geo-db.p.rapidapi.com");
//act
IRestResponse response = client.Execute(request);
//var content = response.Content;
//Console.WriteLine(content);
//Console.ReadKey();
}
}
}

POST function in RestSharp

I want to POST a file to an API by RestSharp, but the Method.Post encounter error as cannot convert from 'RestSharp.Method' to 'string?', and the error for the Method.POST is 'Method' does not contain a definition for 'POST'?
using RestSharp;
using System;
using System.Net;
using System.Net.Http;
namespace UploadToAzure
{
class Program
{
static void Main()
{
var client = new RestClient("http://localhost:7071/api/Function1");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddFile("File", "/D:/sample Files/audio0001.mp3");
IRestResponse response = (IRestResponse)client.Execute(request);
Console.WriteLine(response.Content);
}
}
}
Thanks for your answers!
It solved when I add string of destination to RestRequest and change IRestResponse to RestResponse. In addition correct the path of file.
using RestSharp;
using System;
using System.Net;
using System.Net.Http;
namespace UploadToAzure
{
class Program
{
static void Main()
{
var client = new RestClient("http://localhost:7071/api/Function1");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddFile("File", #"D:/sample Files/audio0001.mp3");
RestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
}
}
I had similar issue, but solved it by doing the following two things
Changed POST to Post.
Putting Method.Post in double quotes "", i.e treating it as a string.

Google Sheets API v4, SocketException: An existing connection was forcibly closed by the remote host

I have gone through many solutions. I also tried one solution here, but it did not work for me. So please don't mark this one as duplicate. I am working with Google Sheets API v4, and I got the following exceptions:
System.AggregateException: 'One or more errors occurred.'
Inner Exceptions:
HttpRequestException: An error occurred while sending the request.
WebException: The underlying connection was closed: An unexpected error occurred on a send.
IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
SocketException: An existing connection was forcibly closed by the remote host
when I try to get the result of HttpResponseMessage. Below are my codes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Http;
using System.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Security;
using System.Net.Http.Headers;
using System.Security.Cryptography.X509Certificates;
namespace ConsoleApp3
{
static class Program
{
static string _apiKey;
static string _sheetID;
static string _baseUrl;
static HttpClient _client;
static Program()
{
_apiKey = ConfigurationManager.AppSettings["apiKey"];
_sheetID = ConfigurationManager.AppSettings["sheetID"];
_client = new HttpClient();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
_baseUrl = "https://sheets.googleapis.com/v4/spreadsheets/{0}/values/{1}!{2}";
}
static void Main(string[] args)
{
using(HttpRequestMessage __request = new HttpRequestMessage())
{
__request.Method = HttpMethod.Post;
__request.RequestUri = new Uri(string.Format(_baseUrl, _sheetID, "Sheet1", "A1:D3"));
Dictionary<string, object> __parameters = new Dictionary<string, object>();
__parameters.Add("key", _apiKey);
__request.Content = new StringContent(__parameters.ToJson(), Encoding.UTF8, "application/json");
using (HttpResponseMessage ___response = _client.SendAsync(__request).Result) // Error Here
{
}
}
Console.ReadKey();
}
}
}
It may be an issue with URL encoding of the ":" character in your request
use System.Web.HttpUtility.UrlEncode() to make sure any characters in your sheetId, sheet name or cell location are encoded correctly.
In your code this line;
__request.RequestUri = new Uri(string.Format(_baseUrl, HttpUtility.UrlEncode(_sheetID), "Sheet1", HttpUtility.UrlEncode("A1:D3")));

Web API: FromBody always null

I'm trying to develop a web API, and when I test the POST method, the body is always null. I have tried everything when sending the request:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:1748/api/SomeAPI");
req.Method = "post";;
var aaa = Encoding.Default.GetBytes("Test");
req.ContentType = "application/xml";
req.ContentLength = aaa.Length;
req.GetRequestStream().Write(aaa, 0, aaa.Length);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
using (System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream())) {
Console.WriteLine(sr.ReadToEnd());
}
I use a breakpoint, and the API is called properly, but the body member is always null:
[HttpPost]
public void Post([FromBody]String test) {
}
try
[HttpPost]
public void SomeApi()
{
var test = HttpContext.Current.Request.Form["Test"];
}
If u send correctly the value,this will work 100%
Your Content Type is set to XML so you must pass the data as XML. This means wrapping your data in <string> element.
I would recommend using RestSharp (http://restsharp.org/) for making WebAPI calls from .Net.
var client = new RestClient("http://localhost:1748/");
var request = new RestRequest("api/SomeAPI", Method.POST);
request.AddBody("Test");
var response = client.Execute(request);
Update
I have created a sample project and it works absolutely fine:
Server side:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class HomeController : ApiController
{
[Route("api/TestAPI")]
[HttpPost]
public IHttpActionResult Post([FromBody]String test)
{
return Ok(string.Format("You passed {0}.", test));
}
}
}
Client side:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:1748/api/TestAPI");
req.Method = "post"; ;
var aaa = Encoding.Default.GetBytes("\"Test\"");
req.ContentType = "application/json";
req.ContentLength = aaa.Length;
req.GetRequestStream().Write(aaa, 0, aaa.Length);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
using (System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream()))
{
Console.WriteLine(sr.ReadToEnd());
}
}
}
}
After installing the WEB API service in IIS and running the console app it prints:
"You passed Test."
Please note the quotes around the response.
If you want to use XML then you need to modify the content type and data you are sending:
var aaa = Encoding.Default.GetBytes("<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Test</string>");
The response you will get is
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">You passed Test.</string>
Both samples in the debugger will have correct value passed in the test parameter.
Two things to try, 1st, try your request using a tried and tested tool like Postman. This will eliminate any chance your request is malformed in any way. 2nd, try changing your ContentType to text/plain. It's possible the request pipeline is seeing application/xml but your request body is invalid xml which really should be a bad request but is just being serialized as null.

authorization header does not have the right format

Akamai api using purge my url i got eror he authorization header does not have the right format
getting error response httpresponse any one tell how to add header authorization in c# tell how to solve the issue ,,tell me how to call akamai api in our project .i have accesstoken and cilent token secret key also how to add this token in this header section
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Http;
using System.Web.Script.Serialization;
using System.Net.Http.Headers;
public partial class Purge : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
purge();
}
public async static void purge()
{
var baseAddress = new Uri(" https://akab-wbrwrbgi6t5urrvg-ohjpi4v6gxsib5aa.purge.akamaiapis.net/");
using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("akab-jbl3s3ptctwvocrr-3fawkhddo47udqlg");
// httpClient.DefaultRequestHeaders.ExpectContinue = false;
using (var content = new StringContent("{ \"objects\": [ \"http://hindi.eenaduindia.com/News/National/2016/03/15150007/video-viral-of-a-girl-creating-ruckus-in-hyderabad.vpf\" ], \"action\": \"remove\", \"type\": \"arl\", \"domain\": \"production\"}", System.Text.Encoding.Default, "application/json"))
{
using (var response = await httpClient.PostAsync("ccu/v2/queues/default", content))
{
string responseData = await response.Content.ReadAsStringAsync();
var b = responseData.Replace('"', ' ');
var r = b.Split(',', '\n');
// Response.Write(r[1]);
}
}
}
}
}
You need to use an Akamai signing library. There is a library for C# here:
https://github.com/akamai-open/AkamaiOPEN-edgegrid-C-Sharp
The library's README includes sample code to get started integrating it into your system.
Thanks,
Kirsten

Categories