(400) Bad Request on Azure server while communicating with service - azure

I have a website and service in Azure webrole. The application uses a ServiceCommunicator class to communicate with the Service. The following code is working fine on my local machine..
private string _url;
public ServiceCommunicator(string url)
{
_url = url;
}
public object GetDataFromService()
{
//create request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
request.Method = "GET";
request.ContentLength = 0;
//get response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
But when this is deployed on cloud (it uses Server 2008 R2 Enterprise) the code throws following exception
The remote server returned an error: (400) Bad Request.
I am unable to understand why is it happening as the code works properly on local machine.

Related

Call API from .NETCOre3.1 returns The SSL connection could not be established

I am trying to call an web page with SSL certificate as you can see below :
public string GetToken()
{
using (var httpClientHandler = new HttpClientHandler())
{
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
httpClientHandler.SslProtocols = System.Security.Authentication.SslProtocols.Tls;
using (var httpClient = new HttpClient(httpClientHandler))
{
HttpResponseMessage response = httpClient.GetAsync("https://pgsb.iran.gov.ir").Result;
return "ok";
}
}
}
When I call my controller in .NETCore 3.1 I get this error.
When I call the website using POSTMAN success response returned But when I call the website using .NETCORE hosted by IIS I get the above error .
As a detail I want to add when I call the website using Angular I get this error in console windows :
no 'access-control-allow-origin' header is present on the requested resource.

Blazor application is getting Forbidden (403) when calling an external API (which works fine in PostMan)

Visual Studio 2019, .NET 3.0 preview, Created a blazor application. Trying to get weather data from https://api.weather.gov/gridpoints/ALY/59,14/forecast.
I am using HttpClient in C#. This is getting forbidden (403) response
Tried to add CORS policty
private async Task<IWeatherDotGovForecast> RetrieveForecast()
{
string url = #"https://api.weather.gov/gridpoints/ALY/59,14/forecast";
var response = await _httpClient.GetAsync(url);
if (response != null)
{
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<WeatherDotGovForecast>(jsonString);
}
//return await _httpClient.GetJsonAsync<WeatherDotGovForecast>
// ("https://api.weather.gov/gridpoints/ALY/59,14/forecast");
return null;
}
I expected JSON data from https://api.weather.gov/gridpoints/ALY/59,14/forecast
Instead, I am getting Forbidden (403) status code
Your problem is not related to Blazor but weather.gov requires a User-Agent header in any HTTP request.
Applications accessing resources on weather.gov now need to provide a User-Agent header in any HTTP request. Requests without a user agent are automatically blocked. We have implemented this usage policy due to a small number of clients utilizing resources far in excess of what most would consider reasonable.
Use something like this:
var _httpClient = new HttpClient();
string url = #"https://api.weather.gov/gridpoints/ALY/59,14/forecast";
_httpClient.DefaultRequestHeaders.Add("User-Agent", "posterlagerkarte");
var response = await _httpClient.GetAsync(url);

Microsoft Bot Framework - Call from Azure app service to external Web API

I had a Microsoft Bot Framework project that connect to Web API(that not hosted in azure).
in local host everything was work fine. but when i was deployed the Bot to an Azure app service. it's seem that the call is failed(and the Bot not return any response).
this is my post request:
public static string Post(List<ActionInputParams> data, string url)
{
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/json;charset=utf-8";
try
{
var res = wc.UploadString(url, "POST", JsonConvert.SerializeObject(data));
return res;
}
catch (Exception ex)
{
return "error " + ex.Message;
}
}
}
my question: there is a problem to call to external Web API from Azure app service? or i just missing something?
in the "log stream" i getting a 500 error:
HTTP Error 500.0 - Internal Server Error
The page cannot be displayed because an internal server error has occurred.

HttpWebRequest with client certificate fails

I am using Visual Studio Mac (latest version) and need to fetch data from an IIs server (vaersion 10) with a GET request and by passing a client certificate.
Unfortunately the IIs answers with an RST packet and shows the error:
The I/O operation has been aborted becourse of either a thread exit or an application request.
I know apple uses ATS (I am using iOS 10.3.3).
I guess this has something to do with the client certificate and IIS not accepting it.
Can someone point me to a differnt mono api where I can append the client cert to a GET request?
My code so far is as follows (with request.GetResponse() waiting until timeout...):
X509Certificate2Collection certificates = new X509Certificate2Collection (certificate);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.uriString);
request.ClientCertificates = certificates;
request.Method = "GET";
request.ContentType = "application/json";
request.Accept = "application/json";
request.UserAgent = UserAgentString;
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version11;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse ())
{
this.webResponse = response;
stream = response.GetResponseStream ();
}

Socket handle leak happening on Azure Web App

I have been stuck in one issue. I am getting error of "Unable to connect to the remote server. An attempt was made to access a socket in a way forbidden by its access permissions".
After searching on web and taking help of azure support, I came to know that if Web App reaches outbound connection limit of azure web app instance, it refuses connections or kill extra connections. Here is the image of open socket handles
My application calls third party WebAPI and wcf service. I have written code to close connections after making call to APIs. but it doesn't work for me. I did following code to call Web API.
var request = (HttpWebRequest)WebRequest.Create("www.xyz.com");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = false;
request.Headers.Add("Authorization", "Handshake");
byte[] bodyData;
bodyData = Encoding.UTF8.GetBytes(input_data);
request.ContentLength = bodyData.Length;
request.GetRequestStream().Write(bodyData, 0, bodyData.Length);
request.GetRequestStream().Flush();
request.GetRequestStream().Close();
using (var response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(),
Encoding.UTF8))
{
string output_data = reader.ReadToEnd();
}
response.Close();
}
Could anyone guide me how to get rid on this issue?

Resources