繁体   English   中英

如何验证 WebClient 请求?

[英]How do I authenticate a WebClient request?

我正在使用 webclient 调用我网站上的页面。 我正在尝试将网页的结果放入 pdf,因此我正在尝试获取呈现页面的字符串表示形式。 问题是请求没有经过身份验证,所以我得到的只是一个登录屏幕。 我已将 UseDefaultCredentials 属性设置为 true,但仍然得到相同的结果。 下面是我的代码的一部分:

 WebClient webClient = new WebClient();
 webClient.Encoding = Encoding.UTF8;

 webClient.UseDefaultCredentials = true;
 return Encoding.UTF8.GetString(webClient.UploadValues(link, "POST",form));

您需要为 WebClient 对象提供凭据。 像这样的东西...

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

您使用的是哪种身份验证? 如果它是表单身份验证,那么充其量,您必须找到 .ASPXAUTH cookie 并将其传递到WebClient请求中。

在最坏的情况下,它不会起作用。

Public Function getWeb(ByRef sURL As String) As String
    Dim myWebClient As New System.Net.WebClient()

    Try
        Dim myCredentialCache As New System.Net.CredentialCache()
        Dim myURI As New Uri(sURL)
        myCredentialCache.Add(myURI, "ntlm", System.Net.CredentialCache.DefaultNetworkCredentials)
        myWebClient.Encoding = System.Text.Encoding.UTF8
        myWebClient.Credentials = myCredentialCache
        Return myWebClient.DownloadString(myURI)
    Catch ex As Exception
        Return "Exception " & ex.ToString()
    End Try
End Function

这帮助我调用了使用 cookie 身份验证的 API。 我已经通过了这样的标题中的授权:

request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));

完整代码:

// utility method to read the cookie value:
        public static string ReadCookie(string cookieName)
        {
            var cookies = HttpContext.Current.Request.Cookies;
            var cookie = cookies.Get(cookieName);
            if (cookie != null)
                return cookie.Value;
            return null;
        }

// using statements where you are creating your webclient
using System.Web.Script.Serialization;
using System.Net;
using System.IO;

// WebClient:

var requestUrl = "<API_url>";
var postRequest = new ClassRoom { name = "kushal seth" };

using (var webClient = new WebClient()) {
      JavaScriptSerializer serializer = new JavaScriptSerializer();
      byte[] requestData = Encoding.ASCII.GetBytes(serializer.Serialize(postRequest));
      HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
      request.Method = "POST";
      request.ContentType = "application/json";                        
      request.ContentLength = requestData.Length;
      request.ContentType = "application/json";
      request.Expect = "application/json";
      request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));
      request.GetRequestStream().Write(requestData, 0, requestData.Length);

      using (var response = (HttpWebResponse)request.GetResponse()) {
         var reader = new StreamReader(response.GetResponseStream());
         var objText = reader.ReadToEnd(); // objText will have the value
      }
}


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM