1 year ago

#336572

test-img

Erica Stockwell-Alpert

HttpWebRequest failing on send through website application, but works in console app

I have a form on my website that makes a basic Get request to an API (managed by the client). It was working for years, until suddenly, it started throwing the error:

The underlying connection was closed: An unexpected error occurred on a send

I've had the client looking into the API, and aren't aware of anything that has changed on their server. Our code hasn't changed either. However, there must be something in the code that is affecting its ability to connect with the server, because I am able to make the Get request in the browser, through postman, and in a brand new console app that we created for testing. Both the website and console app are targeting .Net 4.6.2

Here is the complete code of the console app, which is exactly the same as what's being used within the form submission in my website (with the exception of that I hardcoded the querystring for testing):

internal class Program{

    static void Main(string[] args){
        url = "https://apiurl.com/api/UserSearch";

        string webServiceUrl = url + "?email=test@yopmail.com";
        var response = ServiceHelper.GetHttpWebRequest(webServiceUrl);

        using (Stream stream = response.GetResponseStream())
        {
            StreamReader reader = new StreamReader(stream);
            var jsonResponse = reader.ReadToEnd();

            Console.WriteLine(jsonResponse);
        }
    }
}


public static class ServiceHelper
{
    public static HttpWebResponse GetHttpWebRequest(string requestUrl, NameValueCollection requestHeaders = null)
    {

        var request = (HttpWebRequest)WebRequest.Create(requestUrl);
        if (requestHeaders != null)
        {
            request.Headers.Add(requestHeaders);
        }
        HttpWebResponse response = null;
        try
        {
            response = (HttpWebResponse)request.GetResponse();
        }
        catch (WebException wex)
        {
            Log.Error("ServiceHelper: Error getting Response Stream. "
                    + Environment.NewLine + "RequestUrl = " + requestUrl
                    + Environment.NewLine + GetWebExceptionDetails(wex), typeof(ServiceHelper));
            throw;
        }
        string logMessage = "ServiceHelper: Called " + requestUrl;
        if (response.StatusCode != HttpStatusCode.OK)
        {
            logMessage += " Response Status Code:" + response.StatusCode;
        }
        Log.Info(logMessage, typeof(ServiceHelper));

        return response;
    }
}

Since the basic code for the web request works in the console app, there must be something in the website configuration that's messing with the settings, but I'm not sure where to start looking.

EDIT: Alternate code that uses httpclient instead. This also works in console, fails in the website. Rather than immediately throwing an error, it just seems to hang in the async request indefinitely.

public static class httpclient
{

    // uses asynchronous operations and await
    public static async Task<string> Post(string url, string json)
    {
        // Encode the json data for HTTP
        StringContent data = new StringContent(json, Encoding.UTF8, "application/json");

        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.PostAsync(url, data);
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();

        return responseBody;

    }

    public static async Task<string> Get(string url, string querystring)
    {

        var builder = new UriBuilder(url);
        builder.Query = querystring;

        var uri = builder.ToString();
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(uri);

        string responseBody = await response.Content.ReadAsStringAsync();

        return responseBody;
    }

}

internal class Program{
    static void Main(string[] args){
    string webServiceUrl = "https://apiurl.com/api/UserSearch";;
    var querystring = "?email=" + email;

    var result = httpclient.Get(webServiceUrl, querystring).GetAwaiter().GetResult();
    console.log(results);
    }
}

c#

.net

get

httpwebrequest

webrequest

0 Answers

Your Answer

Accepted video resources