A connection attempt failed because the connected party did not properly -- Using HttpClient - asp.net

I am receiving connection attempt failed to my web api service when I called the service from asp.net mvc application. If I call the service from a browser or from MVC application hosted on another server, it works.
It also works if I host the application in test server or development server.
It doesn't work only when I host the application on that server and call the service from the mvc app.
Any suggestion. Is something on the hosted server is blocking the connection.
using (var client = new HttpClient())
{
string baseUrlFromConfig = ConfigurationManager.AppSettings["webServiceUrl"];
client.BaseAddress = new Uri(baseUrlFromConfig);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Uri myUri = new Uri(baseUrlFromConfig + "api/account/ConfirmEmail?e=" + e + "&code=" + code, UriKind.Absolute);
var response = client.GetAsync(myUri).Result;
if (response.IsSuccessStatusCode)
{
string responseString = response.Content.ReadAsStringAsync().Result;
}
}

Related

azure DevOps basic Auth using HttpClient (FAILED)

i am trying to Authenticate using HttpClient to my Azure Dev organization.
but its always failed.
the only way to achieve success with authentication was using Client Library like this:
VssConnection connection = new VssConnection(new Uri(azureDevOpsOrganizationUrl), new VssClientCredentials());
hope someone can tell me what is it the proper way to auth using username and password only.
UPDATE:
i also tried like this:
string SecurelyStoredUserName = "EmailAddressAsUserName";
SecureString SecurelyStoredPassword = new SecureString();
string PWD = "MyVerySecuredPassword";
PWD.ToList().ForEach(SecurelyStoredPassword.AppendChar);
NetworkCredential myCred = new NetworkCredential(
SecurelyStoredUserName, SecurelyStoredPassword, azureDevOpsOrganizationUrl);
string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(SecurelyStoredUserName + ":" + SecurelyStoredPassword));
HttpClientHandler handler;
handler = new HttpClientHandler() { Credentials = myCred };
HttpClient client;
client = new HttpClient(handler);
client.BaseAddress = new Uri(azureDevOpsOrganizationUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + svcCredentials);
that what i did, but when i tried to do a get/post , i get Error 401 Unauthorized
You can't send a network credential to Azure Devops. It doesn't accept that kind of authentication. You could use a Personal Access token, or use the Active Directory API to get access.
All is explained on the very first "Getting started" pages on how to use the Azure DevOps APIs.
A complete sample for Interactive User+Pass auth is available here.
If you're trying to act as a user on-behalf-of, then you may need to rethink your approach.

.net core 2.0 proxy requests always result in http 407 (Proxy Authentication Required)

I'm trying to make HTTP requests via a WebProxy in a .net core 2.0 web application. The code I've got works fine in .net framework so I know (believe) its not an environmental issue. I've also tried to make the request using both HttpWebRequest and HttpClient but both mechanisms always result in 407 (Proxy Authentication Required) http error in .net core. Its as if in .net core the credentials I'm supplying are always being ignored.
Here is the code I've been using:
public void Test()
{
var cred = new NetworkCredential("xxxxx", "yyyyyy");
var proxyURI = new Uri("http://xxx.xxx.xxx.xxx:80");
var destinationURI = new Uri("http://www.bbc.co.uk");
WebProxy proxy = new WebProxy(proxyURI, false) { UseDefaultCredentials = false, Credentials = cred };
MakeProxyRequestViaHttpWebRequest(proxy, destinationURI);
MakeProxyRequestViaHttpClient(proxy, destinationURI);
}
private void MakeProxyRequestViaHttpClient(WebProxy proxy, Uri destination)
{
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = proxy,
UseProxy = true,
PreAuthenticate = true,
UseDefaultCredentials = false
};
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = client.GetAsync(destination).Result;
if (response.IsSuccessStatusCode)
{
HttpContent content = response.Content;
string htmlData = content.ReadAsStringAsync().Result;
}
else
{
HttpStatusCode code = response.StatusCode;
}
}
private void MakeProxyRequestViaHttpWebRequest(WebProxy proxy, Uri destination)
{
HttpWebRequest req = HttpWebRequest.Create(destination) as HttpWebRequest;
req.UseDefaultCredentials = false;
req.Proxy = proxy;
req.PreAuthenticate = true;
using (WebResponse response = req.GetResponse())
{
using (StreamReader responseStream = new StreamReader(response.GetResponseStream()))
{
string htmlData = responseStream.ReadToEnd();
}
}
}
I've tried the following in .net core but the result is always 407:
Run the code in a console app
Implement IWebProxy and use that as the proxy
Set default values for other properties on WebProxy, HttpClient, etc. (removed on the example above because it works fine on .net standard)
I've run out of ideas and things to try. I have the following questions:
Does the code need to be different between .net core vs .net framework
Are there additional things that need to go into appsettings.json (ie. the config that would have gone into web.config)
Is there any additional configuration code required in Startup.cs
Should I be looking to use an external library
How would I trouble shoot what the issue is? Fiddler doesn't seem to be helping but then I haven't looked to hard at configuring it.

Firewall : Is inbound required for getting response while Outbound rule already there?

I developed one MVC web application which have Web APIs and hosted in Amazon Instance and one windows application for calling those APIs for getting response from that server.
Both Web and Windows applications are developed in asp.net framework 4.5 using c# language.
Windows application is installed in more than 200 client's system which are highly secure servers it selves with all Inbound ports blocked in Firewall.
I am using HttpWebRequest with BindIPEndPoint for calling Web APIs using configured TCP port range [default 7777-7786].
API calls working fine from Windows Application if there are Allow Inbound and Outbound firewall Rules.
But the problem is clients are not allowing me any Inbound Firewall rules, they only allowing Outbound Firewall rules for those port range And Windows application is not working with blocked inbound rules for those port range.
Is it must I need to open Inbound Rule in Firewall for those port range for calling/getting request/response to/from APIs ? If no need of Inbound Firewall rule then please explain Why ?
Below is the API call which use one static TCP port in my Windows Application :
try
{
string address = RevWatchURL;
address = address + "api/GetRevGuardLatestPatch";
HttpWebRequest httpWebRequest = WebRequest.Create(address) as HttpWebRequest;
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = 300000;
httpWebRequest.ServicePoint.BindIPEndPointDelegate =
new BindIPEndPoint(CommonValues.BindIPEndPointCallbackRGPatch);
string enRevGuardUniqueId =
Encryption.EncryptionTechnique(Convert.ToString(UniqueId), null, null);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"UniqueId\":\"" + enRevGuardUniqueId + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
returnVal = streamReader.ReadToEnd();
streamReader.Close();
httpResponse.Close();
}
}
catch (WebException ex)
{
}
finally
{
httpWebRequest.Abort();
}
Obj = JsonConvert.DeserializeObject<CommonValues.RevGuardPatchClass>(returnVal);
}
catch (Exception ex)
{
MessageBox.Show("Error", "API", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
BindIPEndPoint Method:
public static IPEndPoint BindIPEndPointCallbackRGPatch(ServicePoint servicePoint,
IPEndPoint remoteEndPoint, int retryCount)
{
return new IPEndPoint(IPAddress.Any, 7777);
}

Web request to 'https://accounts.google.com/o/oauth2/token' failed. No connection could be ...target machine actively refused it 173.194.70.84:443

I am building an application to fetch data via google analytics. For that purpose I have created a service account information from Google API console and in my .NET webform application successfully able to fetch data via following code:
string clientEmailId = ConfigurationManager.AppSettings.Get("clientEmailId");
string keyFile = AnalyticsKeyFileInitialPath + ConfigurationManager.AppSettings.Get("keyFile");
string keyPass = ConfigurationManager.AppSettings.Get("keyPass");
var desc = GoogleAuthenticationServer.Description;
var key = new X509Certificate2(keyFile, keyPass, X509KeyStorageFlags.Exportable);
var client = new AssertionFlowClient(desc, key) { ServiceAccountId = clientEmailId, Scope = scopeUrl };
var auth = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
var gas = new AnalyticsService(new BaseClientService.Initializer
{
Authenticator = auth
});
//auth.LoadAccessToken();
var accounts = gas.Management.Accounts.List().Fetch();
Now I am calling same code via WCF service but getting following error
Exception Message: Unable to connect to the remote server
Inner Exception: Web request to 'https://accounts.google.com/o/oauth2/token' failed.
Inner Exception: No connection could be made because the target machine actively refused it 173.194.70.84:443
Any idea what I could be doing wrong?

calling a wcf webapi service with basic authentication from an asp.net 2.0 project

I'm working on a project that uses wcf webapi to expose all it's functionality as web services. I then consume these with various views (well two for now). One of these views is a legacy asp.net 2.0 project that will eventually be phased out once this new project has feature parity. I'm trying to consume these services by adding a service reference to the project but can't get it to work because the wcf api uses basic http auth and I can't configure that in the wizard. How do I manually add the service reference to my asp.net project?
Thanks!
When working with WCF Web API, you don't use service references but the new HttpClient instead e.g.:
var client = new HttpClient();
var byteArray = Encoding.ASCII.GetBytes(userName + ":" + password);
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var task = client.GetAsync("http://webapi/contact/1");
var contact = task.ContinueWith(
t => {
return t.Result.Content.ReadAsAsync<Contact>();
}).Unwrap().Result;
If you need to use .NET 2.0, you can use the HttpWebRequest (the HttpClient sample relies on .NET 4.0 as it is part of WCF Web API):
Uri myUri = new Uri("http://webapi/contact/1");
WebRequest myWebRequest = HttpWebRequest.Create(myUri);
HttpWebRequest myHttpWebRequest = (HttpWebRequest)myWebRequest;
NetworkCredential myNetworkCredential =
new NetworkCredential(username, password);
CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(myUri, "Basic", myNetworkCredential);
myHttpWebRequest.PreAuthenticate = true;
myHttpWebRequest.Credentials = myCredentialCache;
WebResponse myWebResponse = myWebRequest.GetResponse();
Stream responseStream = myWebResponse.GetResponseStream();

Resources