I am using HTTPWebRequest
in c# to connect to a server in a .netStandard project.
Code.
byte[] buffer = Encoding.ASCII.GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// Send request
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = buffer.Length;
request.CookieContainer = cookies;
Stream postData = request.GetRequestStream();
postData.Write(buffer, 0, buffer.Length);
postData.Close();
// Get and return response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream Answer = response.GetResponseStream();
StreamReader answer = new StreamReader(Answer);
string ans = answer.ReadToEnd();
I am using the netstandard project in a UWP application. The server is IIS. Now this code works when called from my machine to the server (my machine) using my private IP. When I change the machine that runs the app, and also the server (server is again, on the same machine as the app), I get
System.Net.WebException: An error occurred while sending the request. The text associated with this error code could not be found. A connection with the server could not be established
I have checked that the Url is correct and it works when I do the post in PostMan
. I also have enabled "Private networks Client&Sever capabilities
on UWP app"
What could be the problem?
Edit:
the inner exception is: " An error occurred while sending the request"
Hresult:-2147012867
Status:UnknownError
The solution was to Add loopback exemption for the app. Because of network isolation, some UWP apps are restricted to use IP loopback addresses.
From Step 8 of this link.
Due to network isolation, UWP apps like App Installer are restricted to use IP loopback addresses like http://localhost/. When using local IIS Server, App Installer must be added to the loopback exempt list.
In my case I had to add loopback exemption for MY app.
CheckNetIsolation.exe LoopbackExempt -s
CheckNetIsolation.exe LoopbackExempt -d -n="<your package name>"