Num determinado projeto precisei fazer requisições diretamente via código, e me deparei com alguns problemas: Autenticações (NTLM e Forms) e Cookies.
Consegui resolver a autenticação NTLM forçando o tipo de Credential, e em autenticação Forms, fiz um post com os dados de login. Além, fiz a manipulação do cookie para não ter que fazer a autenticação toda hora. Segue pedaço do código:
85 private HttpWebResponse WebRequestHandler(string url)
86 {
87 HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
88
89 if (ADAuthentication)
90 {
91 CredentialCache cc = new CredentialCache();
92 cc.Add(new Uri(url), "NTLM", CredentialCache.DefaultNetworkCredentials);
93 objRequest.Credentials = cc;
94 objRequest.Method = "GET";
95 }
96 else
97 {
98 if (firstRun)
99 {
100 //Efetua Login na primeira tentativa de conexão com o site
101 string _postString = "";
102 byte[] _postData;
103
104 Dictionary<string, string> _postParams = new Dictionary<string, string>();
105 _postParams.Add("Login1$LoginButton", "Entrar");
106 _postParams.Add("Login1$Password", "");
107 _postParams.Add("Login1$UserName", "system");
108 _postParams.Add("Login1$drpCulture", "");
109 _postParams.Add("__EVENTTARGET", "Login1$LoginButton");
110
111 foreach (KeyValuePair<string, string> pair in _postParams)
112 {
113 _postString += "&" + pair.Key + "=" + pair.Value;
114 }
115
116 _postData = new System.Text.ASCIIEncoding().GetBytes(_postString.Substring(1));
117
118 objRequest.ContentType = "application/x-www-form-urlencoded";
119 objRequest.ContentLength = _postData.Length;
120 objRequest.Referer = "http://" + domain + "/cmspages/logon.aspx";
121 objRequest.Method = "POST";
122
123 System.IO.Stream _outStream = objRequest.GetRequestStream();
124 _outStream.Write(_postData, 0, _postData.Length);
125
126 _outStream.Close();
127
128 }
129 else
130 {
131 objRequest.Method = "GET";
132 }
133 }
134
135 objRequest.AllowAutoRedirect = false;
136 objRequest.KeepAlive = true;
137 objRequest.Timeout = 60000; // 60 segundos.
138 objRequest.CookieContainer = cookieContainer;
139
140 HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
141
142 if (firstRun)
143 {
144 //seta variavel para cookie ser reutilizado.
145 cookieContainer.Add(objResponse.Cookies);
146 firstRun = false;
147 }
148
149 return objResponse;
150 }
--
Bruno Kunioshi
Nenhum comentário:
Postar um comentário