I had a need to do this today for a SharePoint site which uses Forms Based Authentication (FBA). If you try and call an application page without cloning the cookies and assigning a CookieContainer object then the request will fail.
I chose to abstract the job to this handy extension method:
public static CookieContainer GetCookieContainer(this System.Web.HttpRequest SourceHttpRequest, System.Net.HttpWebRequest TargetHttpWebRequest)
{
System.Web.HttpCookieCollection sourceCookies = SourceHttpRequest.Cookies;
if (sourceCookies.Count == 0)
return null;
else
{
CookieContainer cookieContainer = new CookieContainer();
for (int i = 0; i < sourceCookies.Count; i++)
{
System.Web.HttpCookie cSource = sourceCookies[i];
Cookie cookieTarget = new Cookie() { Domain = TargetHttpWebRequest.RequestUri.Host,
Name = cSource.Name,
Path = cSource.Path,
Secure = cSource.Secure,
Value = cSource.Value };
cookieContainer.Add(cookieTarget);
}
return cookieContainer;
}
}
You can then just call it from any HttpRequest object with a target HttpWebRequest object as a parameter, for example:
HttpWebRequest request;
request = (HttpWebRequest)WebRequest.Create(TargetUrl);
request.Method = "GET";
request.Credentials = CredentialCache.DefaultCredentials;
request.CookieContainer = SourceRequest.GetCookieContainer(request);
request.BeginGetResponse(null, null);
where TargetUrl is the Url of the page I am after and SourceRequest is the HttpRequest of the page I am on currently, retrieved via Page.Request.