我今天需要为使用基于表单的身份验证 (FBA) 的 SharePoint 网站执行此操作。如果您尝试调用应用程序页面而不克隆 cookie 并分配 CookieContainer 对象,则请求将失败。
我选择将这项工作抽象为这个方便的扩展方法:
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;
}
}
然后,您可以使用目标 HttpWebRequest 对象作为参数从任何 HttpRequest 对象调用它,例如:
HttpWebRequest request;
request = (HttpWebRequest)WebRequest.Create(TargetUrl);
request.Method = "GET";
request.Credentials = CredentialCache.DefaultCredentials;
request.CookieContainer = SourceRequest.GetCookieContainer(request);
request.BeginGetResponse(null, null);
其中 TargetUrl 是我所关注的页面的 Url,SourceRequest 是我当前所在页面的 HttpRequest,通过 Page.Request 检索。