簡體   English   中英

HttpWebRequest不傳遞憑據簡單表單身份驗證

[英]HttpWebRequest not passing Credentials simple form authentication

我的代碼是這樣的

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();

我在我的網站上使用簡單的表單身份驗證 ,我需要驗證此webRequest以通過abcPDF打印pdf,因為我的登錄詳細信息存儲在cookie中我正試圖從那里獲取並添加到我的請求中。 我假設錯誤是在行request.Credentials = new NetworkCredential("username", "password");

您說該網站正在使用表單身份驗證 ,但您的請求使用的是基本身份驗證憑據:

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

您需要將網站切換到基本身份驗證,或者對登錄頁面執行POST請求以獲取會話cookie /令牌以在后續請求中使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM