Webrequest looks identical but won't log in? - c#

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.

Related

Emulating a web page form POST submission through C#

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.

C# - Sending and receiving HTTP Requests to REST service

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.

Passing querystring parameters in OpenPaths.cc api call with OAuth not working

I am trying to call the OpenPaths.cc rest service API which requires 2-legged OAuth. For this I use the DevDefined.OAuth library (I tried the nuget package and the latest from github). It works when I don't pass parameters in the querystring but returns 400 NOT AUTHORIZED when I do pass parameters.
Working sample with no parameters:
public class OpenPathsRequest
{
private const string accessKey = "your personal access key";
private const string secretKey = "your personal secret";
private const string url = "https://openpaths.cc/api/1";
private OAuthSession session;
public OpenPathsRequest()
{
var consumerContext = new OAuthConsumerContext
{
ConsumerKey = accessKey,
ConsumerSecret = secretKey,
SignatureMethod = SignatureMethod.HmacSha1,
UseHeaderForOAuthParameters = true
};
session = new OAuthSession(consumerContext, url, url, url);
}
private string GetWebResponseAsString(HttpWebResponse response)
{
Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new StreamReader(response.GetResponseStream(), enc);
return loResponseStream.ReadToEnd();
}
public string GetResponse()
{
HttpWebResponse response = session.Request().Get().ForUrl(url).ToWebResponse();
var result = GetWebResponseAsString(response);
return result;
}
}
class Program
{
static void Main(string[] args)
{
// create new OpenPathsRequest and get result
var request = new OpenPathsRequest();
var response = request.GetResponse();
Console.WriteLine(response);
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
But when I change the GetResponse method and pass in 2 parameters (start_time and end_time) like so:
public string GetResponse()
{
HttpWebResponse response = session.Request().Get().ForUrl(url).WithQueryParameters(
new { start_time = 1364962612, end_time = 1364991412 }).ToWebResponse();
var result = GetWebResponseAsString(response);
return result;
}
Which results in the following HTTP request (consumer key omitted):
GET https://openpaths.cc/api/1?start_time=1364962612&end_time=1364991412 HTTP/1.1
Authorization: OAuth oauth_nonce="7b5da37a-6227-4ded-ae8b-a695e789ef90",oauth_consumer_key="**********",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1365058952",oauth_version="1.0",oauth_signature="tAk4KMj%2FsiG6BTLSmvDNKXbBpNs%3D"
Host: openpaths.cc
Connection: Keep-Alive
I get the an error response:
HTTP/1.1 400 Bad Request
Date: Thu, 04 Apr 2013 07:03:26 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
Content-Length: 19
Server: TornadoServer/2.0
Set-Cookie: _xsrf=bf20487382b64eeb8646d31b0770db85; Path=/
Set-Cookie: session_id=ZTk2Mjk1MzIzNWNiMmRjMTY1ZmY5Y2ExNWUwMGY5ZTAxZmY1NGIyODljZGJiNzRlMmIyMWI4NTA3YzUwYWJlYg==|1365059006|7459a7ff95039279e9686ceb76b58918fd9f3e48; expires=Thu, 04 Apr 2013 07:18:26 GMT; Path=/
400: NOT AUTHORIZED
All help would be appreciated very much. Thanks in advance.
Harmen
Solved! Apparently OpenPaths.cc api requires signing WITHOUT the additional query parameters in the signature base string. I believe this is not according to OAuth specs, is it? Anyway, with DevDefined.OAuth i can easily solve this by calling SignWithoutToken before calling WithQueryParameters like so:
public string GetResponse()
{
HttpWebResponse response = session.Request().Get().ForUrl(url).
SignWithoutToken().
WithQueryParameters(new { start_time = 1364962612, end_time = 1364991412 }).
ToWebResponse();
var result = GetWebResponseAsString(response);
return result;
}

Logging into a website automatically in Visual C#? (No WebBrowser)

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.

Silverlight 5 + Internet Explorer 9 using old Content-Type from POST in a subsequent GET?

We've been running into a super annoying problem at work. After our Silverlight application makes it's login POST the next GET that we send fails with a NotFoundException. This only happens when using the Silverlight 5 runtime and only happens in Internet Explorer 9. I have tested now with Silverlight 4 as well as Chrome, Firefox, Opera and Safari, and IE9/SL5 is the only bad combination.
Here are the headers of our login POST:
POST /login HTTP/1.1
Accept: application/xml
Referer: http://localhost:8080/censored.xap?timestamp=1326148328000
Accept-Language: en-CA
Content-Length: 38
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Host: localhost:8080
Connection: Keep-Alive
Pragma: no-cache
Cookie: JSESSIONID=DEFEAFD35E9B067A79F772C166937750
Here are the headers of our next GET:
GET /user/current HTTP/1.1
Accept: application/xml
Referer: http://localhost:8080/censored.xap?timestamp=1326148328000
Accept-Language: en-CA
Content-Length: 38
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Host: localhost:8080
Proxy-Connection: Keep-Alive
Pragma: no-cache
Cookie: JSESSIONID=5C57C93458E80E5975470F703B4A483C
Notice that the Content-Type and Content-Length are identical, even though:
You aren't allowed to use Content-Type or Content-Length on a GET
The content length is actually different in the GET request so it's obviously the old value
Anyone else running into this?
UPDATE:
It only occurs when using BrowserHttp.
Here is some sample client code:
using System;
using System.IO;
using System.Net;
using System.Net.Browser;
using System.Windows.Controls;
namespace NetworkTest
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
HttpWebRequest request = (HttpWebRequest)WebRequestCreator.BrowserHttp.Create(new Uri("http://localhost:59050/Home/Login"));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(result =>
{
var rq = result.AsyncState as HttpWebRequest;
using (var stream = rq.EndGetRequestStream(result))
{
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine("username=test&password=test");
writer.Flush();
writer.Close();
}
rq.BeginGetResponse(
r =>
{
try
{
rq.EndGetResponse(r);
}
catch
{
}
}, rq);
}, request);
}
}
}
Sample server code (from ASP MVC 3):
using System.Web.Mvc;
namespace TestServer.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Login(string test)
{
return RedirectToAction("Index");
}
}
}
You end up seeing a POST to login which is a successful request. You get redirected back to the index page and that GET still contains the Content-Type and Content-Length from the POST and so it fails.
Full solution is available at http://www.mikecousins.com/files/NetworkTest.zip
It works for me.
Here is the steps that I have done with your project.
Set specific port 59050 since you hard-coded the URL but use auto-assigned port.
Added Silverlight project to WebServer (Running from Casini is better than running from file. )
Changed _Layout.cshtml as below to add SL object
#ViewBag.Title
NetworkTest
html, body {
height: 100%;
overflow: auto;
}
body {
padding: 0;
margin: 0;
}
#silverlightControlHost {
height: 100%;
text-align:center;
}
function onSilverlightError(sender, args) {
var appSource = "";
if (sender != null && sender != 0) {
appSource = sender.getHost().Source;
}
var errorType = args.ErrorType;
var iErrorCode = args.ErrorCode;
if (errorType == "ImageError" || errorType == "MediaError") {
return;
}
var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n";
errMsg += "Code: " + iErrorCode + " \n";
errMsg += "Category: " + errorType + " \n";
errMsg += "Message: " + args.ErrorMessage + " \n";
if (errorType == "ParserError") {
errMsg += "File: " + args.xamlFile + " \n";
errMsg += "Line: " + args.lineNumber + " \n";
errMsg += "Position: " + args.charPosition + " \n";
}
else if (errorType == "RuntimeError") {
if (args.lineNumber != 0) {
errMsg += "Line: " + args.lineNumber + " \n";
errMsg += "Position: " + args.charPosition + " \n";
}
errMsg += "MethodName: " + args.methodName + " \n";
}
throw new Error(errMsg);
}
</script>
My MVC Application
#Html.Partial("_LogOnPartial")
#Html.ActionLink("Home", "Index", "Home")
#Html.ActionLink("About", "About", "Home")
#RenderBody()
4.Check "Silverlight" in Web tab to enable the Silverlight debugging.
5. Put the breakpoint at rq.EndGetResponse() (line 34) in MainPage.xaml.cs.
6. Run the app (Observe: This breakpoint is going to get hit. )
Im testing with SL5 and IE9.

Categories