I have implemented following method to get JsessioniD from the Cookies. WebSite uses form authentication.
Here is what I have implemented.
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
using(var client= new CookieAwareWebClient())
{
var values= new NameValueCollection
{
{"username","admin"},
{"password","admin"},
};
client.UploadValues("myURL/j_security_check",values);
WebHeaderCollection myWebHeaderCollection = client.ResponseHeaders;
for (int i=0; i < myWebHeaderCollection.Count; i++)
Console.WriteLine ("\t" + myWebHeaderCollection.GetKey(i) + " = " + myWebHeaderCollection.Get(i));
};
}
CookieAwareWebClient Class is implemented as follows:
public class CookieAwareWebClient : WebClient
{
public CookieAwareWebClient()
{
CookieContainer = new CookieContainer();
}
public CookieContainer CookieContainer { get; private set; }
protected override WebRequest GetWebRequest(Uri address)
{
var request = (HttpWebRequest)base.GetWebRequest(address);
request.CookieContainer = CookieContainer;
return request;
}
}
My question is how to get only JsessionID?
You could store the response cookies in a separate property:
public class CookieAwareWebClient : WebClient
{
public CookieAwareWebClient()
{
CookieContainer = new CookieContainer();
this.ResponseCookies = new CookieCollection();
}
public CookieContainer CookieContainer { get; private set; }
public CookieCollection ResponseCookies { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
var request = (HttpWebRequest)base.GetWebRequest(address);
request.CookieContainer = CookieContainer;
return request;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
var response = (HttpWebResponse)base.GetWebResponse(request);
this.ResponseCookies = response.Cookies;
return response;
}
}
and then:
client.UploadValues("myURL/j_security_check",values);
Cookie jSessionID = client.ResponseCookies["JSESSIONID"];
if (jSessionID != null)
{
// The server set a cookie called JSESSIONID, you can use it here:
string value = jSessionID.Value;
}
Modified class for async operations only:
public class CookieAwareWebClient : WebClient
{
public string ResponseCookies { get; private set; }
protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
{
var response = base.GetWebResponse(request, result);
this.ResponseCookies = response.Headers["Set-Cookie"];
return response;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With