每次调用时,C#HttpClient都会返回错误500(内部服务器错误)

时间:2016-09-06 14:20:29

标签: c# httpclient

我的Web应用程序使用HttpClient连接到后端。通常它可以工作,但每10 = 15次呼叫出现错误500。当重新加载页面时,它就可以了。该错误出现在使用HttpClient对象与后端建立连接的代码中。我的网络应用程序使用 Unity作为IOC

我在当前代码之前做了一些试验: - HttpClientHelper有静态字段static HttpClient httpClient,它没有在代码中放置

但仍然出现错误500.

但是:当我从外部应用程序(如Fiddler)进行大量调用时,错误不会出现。我做了大约150次快速通话,没有出现错误。

UPDATE1:

我对提琴手的要求是:

GET http://www.zzz.com/methodA HTTP/1.1
Authorization: Basic **********************
Accept: application/json
Accept-Language: en-US, en; q=0.5
Host:www.zzz.com

来自提琴手的回应是:

HTTP/1.1 500 Internal Server Error
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 06 Sep 2016 14:06:34 GMT
Content-Length: 36

{"Message":"An error has occurred."}

更新2:

我更改了代码,因此httpClient是一个静态属性。但仍然是同一个问题。 HttpClientHelper类的代码是从async / await启动的,也许这是个问题?

UPDATE3: 我创建了新帖子,它更详细: https://stackoverflow.com/questions/39367225/how-to-syncronize-static-valiable-inside-async-await-methods-httpclient-error-5 欢迎您加入cotinue;)

我目前的连接类是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace MicrositeEngine.Common.Helpers
{
    /// <summary>
    /// Helper class for http calls
    /// </summary>
    public class HttpClientHelper
    {
        private IDictionary<string, string> _customHeaders { get; set; }

        public HttpClientHelper() { }

        public HttpClientHelper(IDictionary<string, string> customHeader)
        {
            _customHeaders = customHeader;
        }

        /// <summary>
        /// Asychronously download string data from given url
        /// </summary>
        /// <param name="url">Place for download string from</param>
        /// <returns>String data downloaded from url</returns>
        public async Task<string> GetStringAsync(string url)
        {
            HttpResponseMessage response = null;

            using (HttpClient httpClient = CreateHttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(HttpRequestConsts.ContentTypeJson));
                httpClient.DefaultRequestHeaders.Add("Connection", "keep-alive");
                httpClient.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.5");

                response = await httpClient.GetAsync(url).ConfigureAwait(true);
                response.EnsureSuccessStatusCode();
            }

            return await response.Content.ReadAsStringAsync().ConfigureAwait(true);
        }

        /// <summary>
        /// Asychronously download byte array data from given url
        /// </summary>
        /// <param name="url">Place for download byte array from</param>
        /// <returns>Byte array data downloaded from url</returns>
        public async Task<byte[]> GetByteArrayAsync(string url)
        {
            HttpResponseMessage response = null;

            using (HttpClient httpClient = CreateHttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(HttpRequestConsts.ContentTypeJson));
                httpClient.DefaultRequestHeaders.Add("Connection", "keep-alive");
                httpClient.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.5");

                response = await httpClient.GetAsync(url).ConfigureAwait(true);
                response.EnsureSuccessStatusCode();
            }

            return await response.Content.ReadAsByteArrayAsync().ConfigureAwait(true);
        }


        private HttpClient CreateHttpClient()
        {
            var clientHandler = new HttpClientHandler { };
            var client = new HttpClient(clientHandler);

            if (_customHeaders != null)
            {
                foreach (var item in _customHeaders)
                {
                    client.DefaultRequestHeaders.Add(item.Key, item.Value);
                }
            }
            client.MaxResponseContentBufferSize = 2147483647; //max possible value

            return client;
        }
    }
}

1 个答案:

答案 0 :(得分:-2)

尝试使用HttpWebRequest而不是HttpClient。

同时用fiddler / wireshark检查你的传出Http-Request的响应。