HttpWebRequest抛出远程服务器返回错误:(500)内部服务器错误

时间:2016-10-03 13:16:57

标签: asp.net-mvc httpwebrequest soapui restsharp digest-authentication

这可能是一个重复的问题,但它与本论坛的内容完全不同。

我有一个Application,它使用外部供应商提供的REST API服务。

  

我一直在用SoapUI 5.2.1工具测试它,我可以连接和   获取数据,

但是当我从我的应用程序中执行相同操作时,此时我已经抛出了这个错误:

(HttpWebResponse)request2.GetResponse();

在此之前我做了什么:

  1. 在SoapUI中尝试5.2.1完美地工作更新
  2. 在浏览器中尝试并完美运行已更新
  3. 我故意给出了错误的密码,然后服务器响应了相应的401 Unauthorized错误
  4. 然后给出了实际密码,然后它回应上面的错误
  5. Fiddler在撰写请求时回复了401 Unauthorized,它命中服务器并自然采取行动。的更新
  6. 我正在使用的准则:

    摘要Authenticator类:

    public class DigestAuthFixer
        {
            private static string _host;
            private static string _user;
            private static string _password;
            private static string _realm;
            private static string _nonce;
            private static string _qop;
            private static string _cnonce;
            private static DateTime _cnonceDate;
            private static int _nc;
    
            public DigestAuthFixer(string host, string user, string password)
            {
                // TODO: Complete member initialization
                _user = user;
                _password = password;
                _host = host;
            }
    
            private string CalculateMd5Hash(
                string input)
            {
                var inputBytes = Encoding.ASCII.GetBytes(input);
                var hash = MD5.Create().ComputeHash(inputBytes);
                var sb = new StringBuilder();
                foreach (var b in hash)
                    sb.Append(b.ToString("x2"));
                return sb.ToString();
            }
    
            private string GrabHeaderVar(
                string varName,
                string header)
            {
                var regHeader = new Regex(string.Format(@"{0}=""([^""]*)""", varName));
                var matchHeader = regHeader.Match(header);
                if (matchHeader.Success)
                    return matchHeader.Groups[1].Value;
                throw new ApplicationException(string.Format("Header {0} not found", varName));
            }
    
            public string GetDigestHeader(
                string dir)
            {
                _nc = _nc + 1;
    
                var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", _user, _realm, _password));
                var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", "GET", dir));
                var digestResponse =
                    CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, _qop, ha2));
    
                //return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " +
                //    "algorithm=MD5, response=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\"",
                //    _user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce);
    
                return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " +
                    "response=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\"",
                    _user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce);
            }
    
            public string GrabResponse(
                string dir)
            {
                var url = _host + dir.TrimStart('/');
                var uri = new Uri(url);
                var request = (HttpWebRequest)WebRequest.Create(uri);
    
    
                // If we've got a recent Auth header, re-use it!
                if (!string.IsNullOrEmpty(_cnonce) &&
                    DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0)
                {
                    var digestHeader = GetDigestHeader(dir);
                    request.Headers.Add("Authorization", digestHeader);
                }
    
                HttpWebResponse response;
                try
                {
                    ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
                    //ServicePointManager.UseNagleAlgorithm = false;
                    //https://holyhoehle.wordpress.com/2010/01/12/webrequest-slow/
                    System.Net.WebRequest.DefaultWebProxy = null;
                    request.Proxy = null;
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException ex)
                {
                    // Try to fix a 401 exception by adding a Authorization header
                    if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
                        throw;
    
                    var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
                    _realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
                    _nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
                    _qop = GrabHeaderVar("qop", wwwAuthenticateHeader);
    
                    _nc = 00000001;
                    _cnonce = new Random().Next(123400, 9999999).ToString();
                    _cnonceDate = DateTime.Now;
    
                    var request2 = (HttpWebRequest)WebRequest.Create(uri);
                    var digestHeader2 = GetDigestHeader(uri.AbsoluteUri);
                    request2.Headers.Add("Authorization", digestHeader2);
                    //https://holyhoehle.wordpress.com/2010/01/12/webrequest-slow/
                    System.Net.WebRequest.DefaultWebProxy = null;
                    request2.Proxy = null;
    
                    try
                    {
                        response = (HttpWebResponse)request2.GetResponse();
                    }
                    catch (Exception er)
                    {
    
                        throw er;
                    }
    
                }
    
                var reader = new StreamReader(response.GetResponseStream());
                return reader.ReadToEnd();
            }
        }
    
        public class DigestAuthenticator : IAuthenticator
        {
            private readonly string _user;
            private readonly string _pass;
            private readonly string _host;
    
            public DigestAuthenticator(string user, string pass, string host)
            {
                _user = user;
                _pass = pass;
                _host = host;
            }
    
            public void Authenticate(IRestClient client, IRestRequest request)
            {
                request.Credentials = new NetworkCredential(_user, _pass);
    
                var url = client.BuildUri(request).ToString();
                var uri = new Uri(url);
    
                var digestAuthFixer = new DigestAuthFixer(_host, _user, _pass);
                digestAuthFixer.GrabResponse(uri.PathAndQuery);
                var digestHeader = digestAuthFixer.GetDigestHeader(uri.PathAndQuery);
                request.AddParameter("Authorization", digestHeader, ParameterType.HttpHeader);
    
            }
        }
    

    Rest代理类:

    public class RESTProxy
        {
    
            string DEFAULT_MODULE = "my-rest";
    
            string DEFAULT_HOST = "http://xxxx.org/";
            string DEFAULT_USER = "xxx:xxxx:xxx";
            string DEFAULT_PASS = "xxxx";
    
            public T Execute<T>(RestRequest request) where T : new()
            {
                //@"http://igvde.nrifintech.com:8181/igv-rest-uat"
                var client = new RestClient(string.Concat(DEFAULT_HOST,DEFAULT_MODULE))
                {
                    Authenticator = new DigestAuthenticator(DEFAULT_USER, DEFAULT_PASS, DEFAULT_HOST)
                };
    
                var response = client.Execute<T>(request);
    
                if (response.ErrorException != null)
                {
                    throw response.ErrorException;
                }
                return response.Data;
            }
    
            public RestRequest initRestRequest(string pRestResourceName, Method pRestServiceVerb, object pRestRequestBody)
            {
                var request = new RestRequest(pRestResourceName, pRestServiceVerb);
                request.RequestFormat = DataFormat.Json;
    
    
                if (pRestRequestBody != null)
                {
                    request.AddBody(pRestRequestBody);
                }
    
                return request;
            }
        }
    

0 个答案:

没有答案