I'm trying to write a C# script that in effect does the same thing as when I submit a form through the UI of a certain webpage. This is on a public page of a site that doesn't use cookies. I looked in Chrome at the Network tab for what happens in the request/response when I submit a comment
and I'm trying to emulate that in C# land:
CommentFormData data = CommentFormData.GenerateRandom();
string json = new JavaScriptSerializer().Serialize(data);
StringContent content = new StringContent(json, Encoding.UTF8);
content.Headers.TryAddWithoutValidation("Accept", "text/javascript, text/html, application/xml, text/xml, */*");
content.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
content.Headers.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.8");
content.Headers.TryAddWithoutValidation("Connection", ";eep-alive");
content.Headers.TryAddWithoutValidation("Content-Length", json.Length.ToString());
content.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
content.Headers.TryAddWithoutValidation("Host", "...");
content.Headers.TryAddWithoutValidation("Origin", "...");
content.Headers.TryAddWithoutValidation("Referer", "...);
content.Headers.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
content.Headers.TryAddWithoutValidation("X-Prototype-Version", "1.6.1");
content.Headers.TryAddWithoutValidation("X-Requested-With", "XMLHttpRequest");
HttpResponseMessage response = await client.PostAsync("...", content);
.....
internal class CommentFormData
{
public string pageID { get; } = "...";
public string comment { get; set; }
public string author { get; set; }
public string email { get; set; }
public int timezone { get; } = -7;
public static CommentFormData GenerateRandom()
{
return new CommentFormData()
{
comment = GenerateRandomString(),
author = GenerateRandomString(),
email = $"{GenerateRandomString()}#gmail.com"
};
}
private static string GenerateRandomString(int length = 100)
{
Random random = new Random();
return new string(Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
}
I am getting back status code 200, but it's not working the same. The response I'm getting is
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
Connection: keep-alive
Keep-Alive: timeout=20
Vary: Accept-Encoding
Date: Sat, 10 Jun 2017 20:44:36 GMT
Server: nginx
Content-Type: text/xml; charset=utf-8
}
so why isn't this working? Any ideas?
I think you should look at the System.Net.Http.HttpsClient class: https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.118).aspx
Use this calss to construct and execute requests asynchronously, and read the contents of their responses.
Related
I have sample code written in C# in Visual Studio on Windows 10 that attempts to send a POST request with custom headers to a service running at http://localhost:9998 which is failing.
When I look at the request the Content-Type header field is being sent as ContentType (no hyphen).
httpRequestMessage:Method: POST, RequestUri: 'http://localhost:9998/',
Version: 1.1, Content: System.Net.Http.ByteArrayContent, Headers: {
ContentType: application/vnd.com.documents4j.any-msword Accept:
application/pdf Converter-Job-Priority: 1000 }response:StatusCode:
500, ReasonPhrase: 'Request failed.', Version: 1.1, Content:
System.Net.Http.StreamContent, Headers: { Connection: close Date:
Sat, 10 Apr 2021 22:39:24 GMT Content-Length: 1031 Content-Type:
text/html; charset=ISO-8859-1 }Press any key to continue . . .
I am wondering if this is the cause of the problem?
I have code written in C# that uses RestSharp and that sends Content-Type correctly and returns a successful result.
I have code written in Java that also sends Content-Type correctly and returns a successful result.
Sample Code 1 [Problem sending Content-Type as ContentType]
using System;
using System.Net;
using System.IO;
using System.Net.Http;
namespace HttpPOST10
{
class Program
{
public static string MyUri { get; private set; }
static void Main(string[] args)
{
// string url = "http://localhost:9998";
string url = "http://localhost:8888"; // Fiddler
Uri myUri = new Uri(url);
string srcFilename = #"C:\temp2\Sample.doc";
string destFileName = #"C:\temp3\Sample-HttpPOST10.pdf";
UploadFile(url, srcFilename, destFileName);
}
private static bool UploadFile(string url, string srcFilename, string destFileName)
{
HttpClient httpClient = new HttpClient();
byte[] data;
data = File.ReadAllBytes(srcFilename);
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Headers = {
{ HttpRequestHeader.ContentType.ToString(), "application/vnd.com.documents4j.any-msword" },
{ HttpRequestHeader.Accept.ToString(), "application/pdf" },
{ "Converter-Job-Priority", "1000" },
// {"User-Agent", "RestSharp/106.11.8.0" }
},
Content = new ByteArrayContent(data)
};
Console.Write("httpRequestMessage:" + httpRequestMessage);
var response = httpClient.SendAsync(httpRequestMessage).Result;
Console.Write("response:" + response);
return true;
}
}
}
Thank you Jimi - have now got a successful response.
httpRequestMessage:Method: POST, RequestUri: 'http://localhost:9998/',
Version: 1.1, Content: System.Net.Http.ByteArrayContent, Headers: {
ContentType: application/vnd.com.documents4j.any-msword Accept:
application/pdf Converter-Job-Priority: 1000 Content-Type:
application/vnd.com.documents4j.any-msword }response:StatusCode: 200,
ReasonPhrase: 'OK', Version: 1.1, Content:
System.Net.Http.StreamContent, Headers: { Vary: Accept-Encoding
Transfer-Encoding: chunked Date: Mon, 12 Apr 2021 03:04:14 GMT
Content-Type: application/pdf
The code change was:
private static bool UploadFile(string url, string srcFilename, string destFileName)
{
HttpClient httpClient = new HttpClient();
byte[] data;
data = File.ReadAllBytes(srcFilename);
HttpContent content = new ByteArrayContent(data);
content.Headers.Add("Content-Type", "application/vnd.com.documents4j.any-msword");
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Headers = {
{ HttpRequestHeader.ContentType.ToString(), "application/vnd.com.documents4j.any-msword" },
{ HttpRequestHeader.Accept.ToString(), "application/pdf" },
{ "Converter-Job-Priority", "1000" },
},
Content = content
};
Console.Write("httpRequestMessage:" + httpRequestMessage);
var response = httpClient.SendAsync(httpRequestMessage).Result;
Console.Write("response:" + response);
return true;
}
I am trying to get info from a website that has no public API. I can't give the website's name because you literally can only sign in with a work account created on their end, so there's no way for other people to test this without my credentials (which I am not giving out).
class Client
{
public string PHPSESSID { get; set; }
public Client()
{
this.Login();
}
public void Login()
{
string csrf;
RestClient client;
RestRequest csrfRequest = new RestRequest(Method.GET);
csrfRequest.AddHeader("accept-language", "en-US,en;q=0.8");
csrfRequest.AddHeader("accept-encoding", "gzip, deflate, br");
csrfRequest.AddHeader("dnt", "1");
csrfRequest.AddHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
csrfRequest.AddHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36");
csrfRequest.AddHeader("upgrade-insecure-csrfRequests", "1");
RestRequest request = new RestRequest(Method.POST);
request.AddHeader("x-requested-with", "XMLHttpRequest");
request.AddHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
request.AddHeader("referer", "{WEBSITE}/login");
request.AddHeader("origin", "{WEBSITE}");
request.AddHeader("host", "{WEBSITE}");
request.AddHeader("dnt", "1");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("content-length", "118");
request.AddHeader("accept-language", "en-US,en;q=0.8");
request.AddHeader("accept-encoding", "gzip, deflate, br");
request.AddHeader("accept", "application/json, text/javascript, */*; q=0.01");
IRestResponse response;
do
{
client = new RestClient("{WEBSITE}/login");
response = client.Execute(csrfRequest);
if (String.IsNullOrEmpty(this.PHPSESSID))
this.setPHPID(response);
csrf = this.FindCSRF(response.Content);
client = new RestClient("{WEBSITE}/login_check");
RestRequest bak = request.Clone();
request.AddCookie("PHPSESSID", this.PHPSESSID);
request.AddParameter("application/x-www-form-urlencoded", "form%5Busername%5D={USERNAME}&form%5Bpassword%5D={PASSWORD}&_csrf_token=" + csrf, ParameterType.RequestBody);
client.FollowRedirects = true;
response = client.Execute(request);
request = bak.Clone();
} while (response.Content.Contains("error"));
}
public string FindCSRF(string input)
{
int find = input.IndexOf("value=", input.IndexOf("_token")) + 8;
int find2 = input.IndexOf('"', find);
--find;
return input.Substring(find, find2-find);
}
public void setPHPID(IRestResponse response)
{
try
{
string cookie = response.Headers.ToList().Find(p => p.Name.Contains("Set-Cookie")).Value.ToString();
if(String.IsNullOrEmpty(cookie))
this.PHPSESSID = response.Cookies[0].Value;
else
{
int cookieStart = cookie.IndexOf("PHPSESSID=") + 10;
this.PHPSESSID = cookie.Substring(cookieStart, cookie.IndexOf(';', cookieStart) - cookieStart);
}
}
catch
{
this.PHPSESSID = response.Cookies[0].Value;
}
}
public void switchBranch(string branchID)
{
RestRequest request = new RestRequest(Method.GET);
request.AddHeader("accept-language", "en-US,en;q=0.8");
request.AddHeader("accept-encoding", "gzip, deflate, br");
request.AddHeader("referer", "{WEBSITE}/message-board");
request.AddHeader("dnt", "1");
request.AddHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
request.AddHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36");
request.AddHeader("upgrade-insecure-requests", "1");
RestRequest branchRequest = new RestRequest(Method.POST);
branchRequest.AddHeader("accept-language", "en-US,en;q=0.8");
branchRequest.AddHeader("accept-encoding", "gzip, deflate, br");
branchRequest.AddHeader("referer", "{WEBSITE}/message-board");
branchRequest.AddHeader("dnt", "1");
branchRequest.AddHeader("content-type", "application/x-www-form-urlencoded");
branchRequest.AddHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36");
branchRequest.AddHeader("x-branchRequested-with", "XMLHttpbranchRequest");
branchRequest.AddHeader("origin", "{WEBSITE}");
branchRequest.AddHeader("accept", "application/json, text/javascript, */*; q=0.01");
IRestResponse response;
RestClient client;
string csrf;
do
{
client = new RestClient("{WEBSITE}/");
client.FollowRedirects = true;
RestRequest acc = request.Clone();
acc.AddCookie("PHPSESSID", this.PHPSESSID);
response = client.Execute(acc);
if (response.Content.Contains("login"))
{
this.Login();
Console.WriteLine("Login Required");
continue;
}
csrf = this.FindCSRF(response.Content);
client = new RestClient("{WEBSITE}/branch-switch");
acc = branchRequest.Clone();
acc.AddCookie("PHPSESSID", this.PHPSESSID);
acc.AddParameter("application/x-www-form-urlencoded", "office_select%5Boffice%5D=" + branchID + "&office_select%5B_token%5D=" + csrf, ParameterType.RequestBody);
} while (response.Content.Contains("error"));
}
}
public static class RequestExt
{
public static RestRequest Clone(this RestRequest req)
{
return req;
}
}
A lot of this I just intercepted from the website using Postman then copied the auto-generated code over, so if there are certain headers that can help, I probably don't know about them.
I mostly fixed the login issues (though I literally have to fail before it gives me a working CSRF token, thus the while loops). The problem is that when I try to go to {WEBSITE} in Client.switchBranch, to start actually doing stuff, it returns a JSON with a redirect to the login page. It doesn't do this in Postman, I have been able to successfully interact with the website and gather information... once or twice (logging in even sometimes fails in the browser).
It seems entirely random to me, but there MUST be some kind of common factor here. I'm guessing it's something to do with the PHPSESSID cookie or the lack of a "keep-alive" connection header (which caused RestSharp to throw an error when I tried to implement it; even if that is the problem, I still don't know how to solve it). The login request and response headers in Chrome's developer tools, intercepting from the website, look something like this.
So I'm writing the client side user authentication code for my Web API ReST service.
This is how the request and response should look like and I've written this code to register a user and it works fine.
Http Request:
POST https://localhost:44305/api/Account/Register HTTP/1.1
Host: localhost:44305
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
Accept: */*
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: https://localhost:44305/
Content-Length: 84
{"Email":"alice#example.com","Password":"Password1!","ConfirmPassword":"Password1!"}
Http Response:
HTTP/1.1 200 OK
Server: Microsoft-IIS/8.0
Date: Wed, 01 Oct 2014 00:57:58 GMT
Content-Length: 0
Code to accomplish this:
byte[] data = Encoding.UTF8.GetBytes("{\"Email\":\"alssice#example.com\"," + "\"Password\":\"Password1!\"," + "\"ConfirmPassword\":\"Password1!\"}");
WebRequest request = WebRequest.Create("http://localhost:8091/api/Account/Register");
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string responseContent = null;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
Console.WriteLine(responseContent);
This works fine and the user account is created in the database but I don't get the response.
The next problem is sending sending the login details to get a bearer token? How can I do this?
This is what the request and response should look like
HTTP REQUEST FOR AUTHENTICATION:
POST https://localhost:44305/Token HTTP/1.1
Host: localhost:44305
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
Accept: */*
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: https://localhost:44305/
Content-Length: 68
grant_type=password&username=alice%40example.com&password=Password1!
HTTP RESPONSE FOR AUTHENTICATION:
HTTP/1.1 200 OK
Content-Length: 669
Content-Type: application/json;charset=UTF-8
Server: Microsoft-IIS/8.0
Date: Wed, 01 Oct 2014 01:22:36 GMT
{
"access_token":"imSXTs2OqSrGWzsFQhIXziFCO3rF...",
"token_type":"bearer",
"expires_in":1209599,
"userName":"alice#example.com",
".issued":"Wed, 01 Oct 2014 01:22:33 GMT",
".expires":"Wed, 15 Oct 2014 01:22:33 GMT"
}
SO how can I send a request for a token?
I'd kindly like to suggest you using HttpClient if you're going for your own http rest client in your app.
Solution using HttpClient and Json.net:
public class TokenResponse
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
public string userName { get; set; }
public string issued { get; set; }
public string expires { get; set; }
}
private async Task Login()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://localhost:44305");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", "alice#example.com"),
new KeyValuePair<string, string>("password", "password1")
});
var result = await client.PostAsync("/token", content);
string resultContent = await result.Content.ReadAsStringAsync();
var tokenResponse = JsonConvert.DeserializeObject<TokenResponse>(resultContent);
}
}
And if you need to use HttpWebRequest:
If this is the case, your solution might look something like the following.
private void Login()
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://localhost:44305/Token");
request.Method = "POST";
request.AllowAutoRedirect = false;
request.Accept = "*/*";
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
StringBuilder postData = new StringBuilder();
postData.Append("grant_type=" + HttpUtility.UrlEncode("password") + "&");
postData.Append("username=" + HttpUtility.UrlEncode("alice#example.com") + "&");
postData.Append("password=" + HttpUtility.UrlEncode("password"));
using (StreamWriter stOut = new StreamWriter(request.GetRequestStream(), Encoding.UTF8))
{
stOut.Write(postData);
stOut.Close();
}
}
Update
Now Im not sure where and how you are trying this. If you're invoking this from a console application main method, make sure the following so you don't have to come back to the same asynchronous context and this should always be invoked from an async method itself:
var result = await client.PostAsync("https://localhost:44305/token", content).ConfigureAwait(false);
I updated my solution in a github gist. It's working for me as it's trying to post the request right away.
Hello everyone I'm facing a bit of a problem that has had me stumped for about an hour. I'm trying to create an app to log in for my work schedule so I don't have to keep opening my web browser and check since my hours change so rapidly. I'm having a bit of an issue logging in though; currently I'm using a webclient to try to do so with my following class:
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace myTLC
{
public class TLC
{
private String employeeID;
private String password;
private String employeeName;
private List<String> values = new List<String>();
public TLC(String ID, String password)
{
this.employeeID = ID;
this.password = password;
}
public String TLC_Login()
{
LoadValues();
using (var client = new CookieAwareWebClient())
{
client.Headers.Add(System.Net.HttpRequestHeader.Accept, "text/html, application/xhtml+xml, */*");
client.Headers.Add(System.Net.HttpRequestHeader.AcceptEncoding, "gzip, deflate");
client.Headers.Add(System.Net.HttpRequestHeader.AcceptLanguage, "en-US");
client.Headers.Add(System.Net.HttpRequestHeader.Referer, "https://mytlc.bestbuy.com/etm/");
client.Headers.Add(System.Net.HttpRequestHeader.UserAgent, "User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
client.Headers.Add(System.Net.HttpRequestHeader.CacheControl, "no-cache");
var parm = new NameValueCollection
{
{"wbat", values[0] },
{"pageAction", "login" },
{ "url_login_token", values[1]},
{"login", employeeID },
{"password", password },
{"localeSelected", "false" },
{"wbXpos", "0" },
{"wbYpos", "0" }
};
byte[] response_array = client.UploadValues("https://mytlc.bestbuy.com/etm/login.jsp", parm);
return Encoding.UTF8.GetString(response_array);
}
}
public void LoadValues()
{
using (var client = new CookieAwareWebClient())
{
String pageSource = client.DownloadString("https://mytlc.bestbuy.com/etm/");
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(pageSource);
if (doc.ParseErrors != null && doc.ParseErrors.Count() > 0)
{
//Error Handling - I'll add it later on.
}
String wbat = doc.DocumentNode.SelectSingleNode(#"//input[#id='wbat']").GetAttributeValue("value", "null");
String url_token = doc.DocumentNode.SelectSingleNode(#"//*[#id='inforLoginWrappingDiv']/input").GetAttributeValue("value", "null");
values.Add(wbat);
values.Add(url_token);
}
}
public String e_ID
{
get { return employeeID; }
set { employeeID = value; }
}
public String e_Pass
{
get { return password; }
set { password = value; }
}
public String e_Name
{
get { return employeeName; }
set { employeeName = value; }
}
}
}
The request data (handled by Google Chrome and inspected in Fiddler) looks like this:
POST https://mytlc.bestbuy.com/etm/login.jsp HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Referer: https://mytlc.bestbuy.com/etm/
Accept-Language: en-US
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: mytlc.bestbuy.com
Content-Length: 167
DNT: 1
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: JSESSIONID=0000HLkYnJDHq9wQwU8qPA90MYq:182bi51ql
wbat=yP6uE%2F7vW9xhvIPEm1Ro6h%2FQNEObayZ6&pageAction=login&url_login_token=-1959600643775&login=xxxx&password=xxxx&localeSelected=false&wbXpos=0&wbYpos=0
(Some numbers in login token are left out and username and pass are left out, for good reasons obviously)
What I can't figure out is what the issue is? I process my request through the WebClient class (That someone here on StackOverflow has posted before, credits to them) I grab all my values I need to pass correctly; I have made sure all the values are correctly being pulled, and I get no error on the login attempt all the program does is redirect back to the login page without any error messages.
Am I missing something in the request guys, or I am completely blind here?
I wouldn't think it would be anything with the .jsp? Meaning that they're using Java so that raw WebRequest wouldn't work because they can't pass Java / Javascript? That's my only thought on why it would not work.
I am trying to log in to a website using Visual C# but I am not sure where to start. Eventually, I want to download a PDF File from the website but I must login to the website as it is password-restricted. The url is below:
https://sso.greatclips.com/authentication/login/login.aspx?ud=1&ApplicationCode=1&ReturnURL=https%3A%2F%2Fwww.salondata.com%2Fv2%2Fwa%2FloginPostBack
I am not sure if it is working. What are my options, and is the code even doing anything?
Here is my code so far. (Note: I do not want to browse the web in the Visual C# App, I want it done in the background)
public static Setup setup = new Setup();
private CookieContainer _jar = new CookieContainer();
public static string password = setup.Password;
public static string username = setup.UserName;
private string _url = "https://sso.greatclips.com/authentication/login/login.aspx";
private string _userAgent;
public Salons()
{
InitializeComponent();
}
private void Salons_Load_1(object sender, EventArgs e)
{
string responseData;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(_url);
webRequest.CookieContainer = _jar;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.UserAgent = _userAgent;
string requestBody = String.Format(
"client_id={0}&password={1}", username, password);
using (StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(requestBody);
lblStatus.Text = "Writing request ...";
requestWriter.Close();
using (HttpWebResponse res = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader responseReader = new StreamReader(res.GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
responseReader.Close();
lblStatus.Text = "Closing request ...";
if (res.StatusCode != HttpStatusCode.OK)
throw new WebException("Logon failed", null, WebExceptionStatus.Success, res);
else
lblStatus.Text = "Successfully logged in!";
}
}
}
}
EDIT:
Request when I click on Sign In Button:
POST http://sso.greatclips.com/authentication/login/login.aspx?ud=1&ApplicationCode=1&ReturnURL=https%3a%2f%2fwww.salondata.com%2fv2%2fwa%2floginPostBack HTTP/1.1
Host: sso.greatclips.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
X-MicrosoftAjax: Delta=true
Cache-Control: no-cache, no-cache
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Referer: http://sso.greatclips.com/authentication/login/login.aspx?ud=1&ApplicationCode=1&ReturnURL=https%3A%2F%2Fwww.salondata.com%2Fv2%2Fwa%2FloginPostBack
Content-Length: 1331
Cookie: stayloggedin=399238; ASP.NET_SessionId=g3tf01mqzgcdbhyoagfz1s55; .ADAuthCookie=2496474AAA6C67DC05253300439E06151F94E728769EA71FBFDB0CD832E772DBA6F5B5220EF7A5C7E79ED7B445EB7DF6C39B9A1E276277BDD3DC9DF2756294157D57C1B926F919F3A87BDE0CDBA8F43E0C8989357A24372DEA39B973A53F89F0EDEE1E2D3B391A785B1AB19FB704B420BD95A5C3505765D51FA865565686F3CF0F74AFD2C2E76146AB14F46BC2E4B21189B721C32DF3A6466631D0326ABB0D95087FF9E2
Pragma: no-cache
ctl00%24ScriptManager1=ctl00%24UpdatePanel1%7Cctl00%24cphMain%24loginMain%24LoginButton&_EVENTTARGET=&_EVENTARGUMENT=&_VIEWSTATE=%2FwEPDwUKMjA3MDY5NDk2Ng9kFgJmD2QWBAIBD2QWBGYPZBYCZg9kFgICAQ8WAh4EVGV4dAUQUmVwb3J0aW5nIENlbnRlcmQCAg9kFgICAQ9kFgICAQ8WAh8ABRpzVGl0bGVCYWNrZ3JvdW5kPScjNUU3MUI2J2QCAw9kFgYCAw8PFgYeCEltYWdlVXJsBRppbWFnZXMvc3BlY3RydW1fYmFubmVyLmpwZx4NQWx0ZXJuYXRlVGV4dAUQUmVwb3J0aW5nIENlbnRlch4HVmlzaWJsZWdkZAIFD2QWAmYPZBYCAgEPDxYEHglCYWNrQ29sb3IJ%2FPz8%2Fx4EXyFTQgIIZBYCAgEPZBYCAgMPZBYCAgEPPCsACgEADxYCHghVc2VyTmFtZQUbc3VkZXNoLnNhcHJhQGdyZWF0Y2xpcHMubmV0ZBYCZg9kFgYCAQ8PFgIfAAUQUmVwb3J0aW5nIENlbnRlcmRkAgUPDxYCHwAFG3N1ZGVzaC5zYXByYUBncmVhdGNsaXBzLm5ldGRkAhkPDxYCHwAFGHdlYm1hc3RlckBncmVhdGNsaXBzLmNvbWRkAgkPDxYCHwAFEUNvcHlyaWdodCDCqSAyMDEyZGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFJ2N0bDAwJGNwaE1haW4kbG9naW5NYWluJGNoa1N0YXlMb2dnZWRJbufuwcvYeS4gDjHhavP572TVdscK&_EVENTVALIDATION=%2FwEWCQL%2B5bxcAr2ailYCkqyM%2BQ0CtvDI7gECpJCinAICzoverwUCjqr%2B%2FAoCocjV5gcCybrK0QNROj0%2BEho3liuMeskLfe3LtC8Zog%3D%3D&ctl00%24cphMain%24loginMain%24UserName=*&ctl00%24cphMain%24loginMain%24UserName_TextBoxWatermarkExtender_ClientState=&ctl00%24cphMain%24loginMain%24Password=*&ctl00%24cphMain%24loginMain%24chkStayLoggedIn=on&__ASYNCPOST=true&ctl00%24cphMain%24loginMain%24LoginButton=Sign%20In
Couple things which can help you
(a) this url also works without SSL (so you will not have a deal with check the right certificate, etc), and for now you can just try to do this work with url http://sso.greatclips.com/authentication/login/login.aspx?ud=1&ApplicationCode=1&ReturnURL=https%3A%2F%2Fwww.salondata.com%2Fv2%2Fwa%2FloginPostBack (http instead of https)
(b) use fiddler tool which allows you to logs the traffic between browser and web server. Just take a look on request which browser sends to server when you click on Sign In button and try to implement the same request in C# code.