HttpWebRequest 无法通过网站应用程序发送,但可以在控制台应用程序中使用

发布于 2025-01-17 01:24:59 字数 3494 浏览 0 评论 0原文

我的网站上有一个表单,可以向 API(由客户端管理)发出基本的 Get 请求。它工作了很多年,直到突然开始抛出错误:

底层连接已关闭:发送时发生意外错误

我已经让客户端查看 API,但没有了解其服务器上发生的任何更改。我们的代码也没有改变。但是,代码中一定有某些内容影响其与服务器连接的能力,因为我能够在浏览器中通过邮递员以及我们为测试创建的全新控制台应用程序发出 Get 请求。网站和控制台应用程序都针对 .Net 4.6.2

这是控制台应用程序的完整代码,它与我的网站中表单提交中使用的代码完全相同(除了我硬编码了查询字符串)测试):

internal class Program{

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

        string webServiceUrl = url + "[email protected]";
        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;
    }
}

由于网络请求的基本代码在控制台应用程序中工作,因此网站配置中一定有某些内容扰乱了设置,但我不确定从哪里开始寻找。

编辑:使用 httpclient 的替代代码。这在控制台中也有效,但在网站中失败。它并没有立即抛出错误,而是似乎无限期地挂在异步请求中。

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);
    }
}

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 protected]";
        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);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文