-1
How do I perform an ASP NET MVC 5 request in this way:
- Method = post;
- Authentication credentials = xxx:yyyyy (i.e., username, followed by two points, followed by password, encrypted in Base64 format);
- Send data on body webrequest in JSON format.
I’ve done several tests and I’d like to know what I might be doing wrong
NetworkCredential credential = new NetworkCredential(usernameAuth, passwordAuth, defaultURL);
CredentialCache cache = new CredentialCache();
cache.Add(new Uri(defaultURL), "Basic", credential);
Console.WriteLine(cache);
/*
var unEncodedString = String.Format("{0}:{1}", usernameAuth, passwordAuth);
var encodedString = Convert.ToBase64String(Encoding.ASCII.GetBytes(unEncodedString));
*/
try
{
WebRequest webRequest = WebRequest.Create(defaultURL);
if (webRequest != null)
{
//webRequest.Credentials = cache;
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.ContentLength = infoDados.Length;
webRequest.PreAuthenticate = true;
webRequest.Credentials = cache;
//enviando dados post
using (var stream = webRequest.GetRequestStream())
{
stream.Write(infoDados, 0, infoDados.Length);
stream.Close();
}
//lendo dados
using (Stream s = webRequest.GetResponse().GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
result = sr.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
In my code:
usernameAuth
: username of the authentication
passwordAuth
: password for authentication
defaultURL
: request submission url
the defaultURL variable has the full url and endpoint path? if yes, try to put in the defaultURL only the domain the application is in, the way you are creating the setting credentials is correct
– João Paulo Amorim
Do you want to send credentials where? In the body of the request or in some header?
– Jéf Bueno