0

My code is like this

Doc doc = new Doc();
string url =  HttpContext.Current.Request.Url.AbsoluteUri;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// required for HttpWebResponse.Cookies
request.CookieContainer = new CookieContainer(); 

request.Credentials = new NetworkCredential("username", "password");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response.Cookies.Count>0) { // includes ASP.NET_SessionId
    bool needsCookie2 = false;
    StringBuilder builder = new StringBuilder("Cookie: ");
    for(int i = 0; i<response.Cookies.Count; ++i) {
        Cookie cookie = response.Cookies[i];
        if(!needsCookie2 && cookie.Version!=1)
             needsCookie2 = true;
        if(i>0)
             builder.Append("; ");
        builder.Append(cookie.ToString());
    }
    builder.Append(!needsCookie2? "\r\n": "\r\nCookie2: $Version=1\r\n");
    doc.HtmlOptions.HttpAdditionalHeaders = builder.ToString();
}

doc.HtmlOptions.NoCookie = true;
doc.HtmlOptions.HostWebBrowser = false;

// cookieless Forms Authentication adds authentication ticket to the URL
int id = doc.AddImageUrl(response.ResponseUri.AbsoluteUri);
doc.Save(HttpContext.Current.Server.MapPath("~/media/pdf/1212.pdf"));
doc.Clear();

I am using simple form authentication in my website and I need to authenticate this webRequest in order to print a pdf through abcPDF, as my login details are stored in cookie i am trying to get it from there and add to my request. I assume the error is in line request.Credentials = new NetworkCredential("username", "password");

4

1 回答 1

2

您说该网站正在使用表单身份验证,但您的请求使用的是基本身份验证凭据:

request.Credentials = new NetworkCredential("username", "password");

您需要将网站切换到基本身份验证,或者对您的登录页面执行 POST 请求以获取会话 cookie/令牌以在后续请求中使用。

于 2013-01-09T13:13:53.813 回答