How to add basic authentication header to WebRequest
Easy. In order to add a basic authentication to your HttpRequest you do this:
string username = "Your username";
string password = "Your password";
string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + svcCredentials);
In basic authentication you need to use Base64 to encode the credentials.
Forcing Basic Authentication in WebRequest
I've just found this very handy little chunk of code to do exactly what you need. It adds the authorization header to the code manually without waiting for the server's challenge.
public void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
}
Use it like this
var request = WebRequest.Create("http://myserver.com/service");
SetBasicAuthHeader(request, userName, password);
var response = request.GetResponse();
Basic authentication with HttpWebRequest
Edit :
Based on the FaizanRabbani comment, i resolved the problem by setting an UserAgent property to the httpwebrequest :
code :
private async Task<WebResponse> ExecuteHttpWebRequest()
{
var selectedMethode = Methode.SelectedItem as TextBlock;
string method = selectedMethode.Text;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Query.Text);
WebHeaderCollection myWebHeaderCollection = webRequest.Headers;
myWebHeaderCollection = BuildHeaderCollection(myWebHeaderCollection);
myWebHeaderCollection = AddAuthorization(myWebHeaderCollection);
webRequest.PreAuthenticate = true;
webRequest.Method = method;
webRequest.UserAgent = "something";
if (webRequest.Method == "POST" || webRequest.Method == "PUT" || webRequest.Method == "PATCH")
{
byte[] data = Encoding.ASCII.GetBytes(Body.Text);
webRequest.ContentLength = data.Length;
using (var stream = webRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
return await webRequest.GetResponseAsync();
}
Related Topics
Reading a C/C++ Data Structure in C# from a Byte Array
Why Doesn't .Net/C# Optimize for Tail-Call Recursion
Casting Interfaces for Deserialization in JSON.Net
Checking for Directory and File Write Permissions in .Net
How to Change a Private Readonly Field in C# Using Reflection
Run Async Method Regularly with Specified Interval
Resolving Instances with ASP.NET Core Di from Within Configureservices
How to Create a Simple Proxy in C#
Detect Windows Version in .Net
How to Get Object Size in Memory
Using String Format to Show Decimal Up to 2 Places or Simple Integer
How to Programmatically Generate Keypress Events in C#
Why Is Multiple Inheritance Not Allowed in Java or C#