示例#1
0
        private static HttpWebRequest CreateWebRequest(Uri uri, AcceptType acceptType,
                                                       int timeout = SearchRequest.DefaultTimeout,
                                                       AuthenticationType authType  = AuthenticationType.CurrentUser,
                                                       string sharePointSiteUrl     = null,
                                                       string username              = null,
                                                       string password              = null,
                                                       SecureString securePassword  = null,
                                                       CookieCollection authCookies = null,
                                                       string accessToken           = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            request.Accept = acceptType == AcceptType.Json ? "application/json;odata=verbose;charset=utf-8" : "application/xml;charset=utf-8";

            request.Timeout           = timeout * 1000;
            request.AllowAutoRedirect = true;

            if (authType == AuthenticationType.CurrentUser)
            {
                request.ApplyDefaultCredentials();
            }
            else if (authType == AuthenticationType.Windows)
            {
                if (String.IsNullOrWhiteSpace(username))
                {
                    throw new ArgumentException("Parameter Username cannot be empty!");
                }

                if (String.IsNullOrWhiteSpace(password) && securePassword == null)
                {
                    throw new ArgumentException("Parameter Password cannot be empty!");
                }

                request.ApplyWindowsCredentials(username, securePassword);
            }
            else if (authType == AuthenticationType.Forms)
            {
                if (String.IsNullOrWhiteSpace(username))
                {
                    throw new ArgumentException("Parameter Username cannot be empty!");
                }

                if (String.IsNullOrWhiteSpace(password))
                {
                    throw new ArgumentException("Parameter Password cannot be empty!");
                }

                request.ApplyFormsCredentials(sharePointSiteUrl, username, password);
            }
            else if (authType == AuthenticationType.SPO || authType == AuthenticationType.Forefront)
            {
                request.ApplyCookieCredentials(authCookies);
            }
            else if (authType == AuthenticationType.SPOManagement)
            {
                request.Headers.Add("Authorization", accessToken);
            }
            return(request);
        }