コード例 #1
0
    public void TestWebHeaderCollectionRemove()
    {
        WebHeaderCollection whc = new WebHeaderCollection();

        whc.Add("some:stuff");
        whc.Remove("some");
        try
        {
            whc.Remove(null);
            Fail("Remove: failed to throw exception for null argument");
        }
        catch (ArgumentNullException)
        {
            // Ok
        }
        try
        {
            whc.Remove("[NotValidHeader?]");
            Fail("Remove: failed to throw exception for invalid header name: '[NotValidHeader?]'");
        }
        catch (ArgumentException)
        {
            // Yep...
        }
        try
        {
            whc.Remove("accept");
            Fail("Remove: failed to throw exception for restricted header 'accept'");
        }
        catch (ArgumentException)
        {
            // Still moving along...
        }
    }
コード例 #2
0
        private byte[] ProcessResponseStream(HttpRequest request, Stream responseStream, WebHeaderCollection webHeaderCollection)
        {
            responseStream.Position = 0;

            if (responseStream.Length != 0)
            {
                var encoding = webHeaderCollection["Content-Encoding"];
                if (encoding != null)
                {
                    if (encoding.IndexOf("gzip") != -1)
                    {
                        responseStream = new GZipStream(responseStream, CompressionMode.Decompress);

                        webHeaderCollection.Remove("Content-Encoding");
                    }
                    else if (encoding.IndexOf("deflate") != -1)
                    {
                        responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);

                        webHeaderCollection.Remove("Content-Encoding");
                    }
                }
            }

            return(responseStream.ToBytes());
        }
コード例 #3
0
ファイル: CurlHttpClient.cs プロジェクト: slpaige/Sonarr
        private byte[] ProcessResponseStream(HttpWebRequest webRequest, Stream responseStream, WebHeaderCollection webHeaderCollection)
        {
            responseStream.Position = 0;

            if (responseStream.Length != 0 && webRequest.AutomaticDecompression != DecompressionMethods.None)
            {
                var encoding = webHeaderCollection["Content-Encoding"];
                if (encoding != null)
                {
                    if (webRequest.AutomaticDecompression.HasFlag(DecompressionMethods.GZip) && encoding.IndexOf("gzip") != -1)
                    {
                        responseStream = new GZipStream(responseStream, CompressionMode.Decompress);

                        webHeaderCollection.Remove("Content-Encoding");
                    }
                    else if (webRequest.AutomaticDecompression.HasFlag(DecompressionMethods.Deflate) && encoding.IndexOf("deflate") != -1)
                    {
                        responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);

                        webHeaderCollection.Remove("Content-Encoding");
                    }
                }
            }

            return(responseStream.ToBytes());
        }
コード例 #4
0
        public static void SetLinkingHeaders(this WebHeaderCollection headers, string requestId, string opId)
        {
            headers.Remove(OPERATION_HEADER);
            headers.Add(OPERATION_HEADER, opId);

            headers.Remove(REQUEST_HEADER);
            headers.Add(REQUEST_HEADER, requestId);
        }
コード例 #5
0
 /// <summary>
 /// Sets the authorization header that should be supplied on every request
 /// </summary>
 /// <param name="scheme">The scheme.</param>
 /// <param name="parameter">The parameter.</param>
 /// <exception cref="System.NotImplementedException"></exception>
 public void SetAuthorizationHeader(string scheme, string parameter)
 {
     if (string.IsNullOrEmpty(parameter))
     {
         _defaultHeaders.Remove(HttpRequestHeader.Authorization);
     }
     else
     {
         _defaultHeaders[HttpRequestHeader.Authorization] = scheme + " " + parameter;
     }
 }
コード例 #6
0
 private void SetHeaderValue(HttpRequestHeader name, string value)
 {
     if (value != null)
     {
         _headers[name] = value;
     }
     else
     {
         _headers.Remove(name);
     }
 }
コード例 #7
0
        public void Remove_HeaderExists_RemovesFromCollection(string name)
        {
            var headers = new WebHeaderCollection()
            {
                { "name", "value" }
            };

            headers.Remove(name);
            Assert.Empty(headers);

            headers.Remove(name);
            Assert.Empty(headers);
        }
コード例 #8
0
        private HttpWebRequest SetupWebClient()
        {
            HttpWebRequest _wc;

            try
            {
                var r = WebRequest.Create(new Uri(_URL));
                _wc = r as HttpWebRequest;
            }
            catch (Exception)
            {
#if DEBUG
                if (Debugger.IsAttached)
                {
                    throw;
                }
#endif
                return(null);
            }
            _wc.Timeout   = _timeout;
            _wc.KeepAlive = false;
            _wc.Referer   = _referrer;
            try
            {
                var accept = _headers.GetValues("Accept");
                if (accept != null)
                {
                    _wc.Accept = accept[0];
                    _headers.Remove("Accept");
                }

                var host = _headers.GetValues("Host");
                if (host != null)
                {
                    _wc.Host = host[0];
                    _headers.Remove("Host");
                }

                _wc.Headers = _headers;
            }
            catch (Exception ex)
            {
                if (System.Windows.Forms.MessageBox.Show("Error when setting headers:\r\n" + ex.Message + "\r\n\r\nContinue?", "Continue?", System.Windows.Forms.MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes)
                {
                    Stop();
                    return(null);
                }
            }

            return(_wc);
        }
コード例 #9
0
        private void SetHeaderValue(HttpRequestHeader name, string value)
        {
            if (value != null)
            {
                _headers[name] = value;
            }
            else
            {
#if PCL || NETFX_CORE || SILVERLIGHT
                throw new PlatformNotSupportedException("Header removal not supported on this platform");
#else
                _headers.Remove(name);
#endif
            }
        }
コード例 #10
0
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            HttpRequestMessageProperty httpRequest = null;

            if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
            {
                httpRequest = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            }

            if (httpRequest == null)
            {
                httpRequest = new HttpRequestMessageProperty()
                {
                    Method             = "GET",
                    SuppressEntityBody = true
                };
                request.Properties.Add(HttpRequestMessageProperty.Name, httpRequest);
            }
            WebHeaderCollection headers = httpRequest.Headers;

            string token = cacheToken ? AppDomainHelper.TokenDictionary.GetToken(oAuth_Url, tenant_Id, client_Id, client_Secret, resource, grant_Type)
                : TokenDictionary.GetNewToken(oAuth_Url, tenant_Id, client_Id, client_Secret, resource, grant_Type).Token;

            //Remove the authorization header if already exists.
            headers.Remove(HttpRequestHeader.Authorization);
            headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
            return(null);
        }
コード例 #11
0
        /// <summary>
        /// Из входящего ответа от сайта делает исходящий ответ для пользователя.
        /// Копирует заголовки, а если есть, то и тело ответа.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="incomingResponse"></param>
        public void SendResponse(HttpListenerContext context, HttpWebResponse incomingResponse)
        {
            WebHeaderCollection headers = incomingResponse.Headers;

            headers.Remove("Content-Length"); // Этот заголовок нельзя передавать в комплекте.
            context.Response.Headers = headers;
            if (incomingResponse.ContentLength > 0)
            {
                Stream       receiveStream = incomingResponse.GetResponseStream();
                MemoryStream ms            = new MemoryStream();
                try
                {
                    receiveStream.CopyTo(ms);
                }
                catch (Exception e) { Console.WriteLine("e>{0:yyyy-MM-dd HH:mm:ss} SendResponse(): {1} {2}", DateTime.Now, e.Message, context.Response.RedirectLocation); }
                context.Response.ContentLength64 = ms.Length; // Восстанавливаем Content-Length
                if (ms.Length > 0)
                {
                    ms.Position = 0;
                    try
                    {
                        ms.CopyTo(context.Response.OutputStream);
                    }
                    catch (Exception e) { Console.WriteLine("e>{0:yyyy-MM-dd HH:mm:ss} SendResponse(): {1} {2}", DateTime.Now, e.Message, context.Response.RedirectLocation); }
                }
            }
            context.Response.OutputStream.Close();
        }
コード例 #12
0
 public static void RemoveHeader(WebHeaderCollection headers)
 {
     if (!string.IsNullOrWhiteSpace(headers["FaultInjectionInfo"]))
     {
         headers.Remove("FaultInjectionInfo");
     }
 }
コード例 #13
0
 public void InitializeRequest(Uri url, Method method, WebHeaderCollection head, int timeout)
 {
     if (url.Scheme.ToLower() == "https")
     {
         ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors) =>
         {
             return(true); //总是接受
         });
         ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
     }
     Request = WebRequest.Create(url) as HttpWebRequest;
     Request.AllowAutoRedirect = true;
     Request.KeepAlive         = false;
     Request.Method            = method.ToString();
     if (head.AllKeys.Contains("user-agent"))
     {
         Request.UserAgent = head.Get("user-agent");
         head.Remove("user-agent");
     }
     foreach (var item in head.AllKeys)
     {
         Request.Headers.Add(item, head.Get(item));
     }
     Request.ContentType = "charset=UTF-8;";
     Request.Timeout     = timeout;
 }
コード例 #14
0
        public void Remove()
        {
            col.Remove("Name1");
            col.Remove("NameNotExist");
            Assert.AreEqual(1, col.Count, "#1");

            /*
             * // this can only be tested in namespace System.Net
             * try {
             *      WebHeaderCollection col2 = new WebHeaderCollection (true);
             *      col2.Add ("Host", "foo");
             *      col2.Remove ("Host");
             *      Assert.Fail ("#2: should fail according to spec");
             * } catch (ArgumentException) {}
             */
        }
コード例 #15
0
        public void Custom_AddThenRemove_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();

            w.Add("name", "value");
            w.Remove("name");
            Assert.Equal(0, w.Count);
        }
コード例 #16
0
 // Token: 0x0600052C RID: 1324 RVA: 0x0001CAE8 File Offset: 0x0001ACE8
 protected override void AddProtocolSpecificHeadersToServerRequest(WebHeaderCollection headers)
 {
     base.AddProtocolSpecificHeadersToServerRequest(headers);
     if (this.proxyForSameOrgExchangeOAuthCallToLowerVersion)
     {
         headers.Remove("X-CommonAccessToken");
     }
 }
コード例 #17
0
 private void SetSpecialHeaders(string headerName, string value)
 {
     _HttpRequestHeaders.Remove(headerName);
     if (value.Length != 0)
     {
         _HttpRequestHeaders.Add(headerName, value);
     }
 }
コード例 #18
0
        /// <summary>
        /// Prepara a requisição antes da solicitação
        /// </summary>
        /// <param name="request"></param>
        private void AddPostDataTo(HttpWebRequest request)
        {
            request.UserAgent = SettingsManager.GetSessionUserAgent();
            WebHeaderCollection myWebHeaderCollection = request.Headers;

            myWebHeaderCollection.Add("Accept-Language", SettingsManager.GetSessionAcceptLanguage());
            myWebHeaderCollection.Add("AcceptCharset", SettingsManager.GetSessionAcceptCharset());
            myWebHeaderCollection.Add("TransferEncoding", SettingsManager.GetSessionTransferEncoding());
            if (extraHeader != null)
            {
                foreach (var kv in extraHeader)
                {
                    if (myWebHeaderCollection.Get(kv.Key) == null)
                    {
                        myWebHeaderCollection.Add(kv.Key, kv.Value);
                    }
                }
            }
            if (toRemoveHeader != null)
            {
                foreach (var r in toRemoveHeader)
                {
                    if (myWebHeaderCollection.Get(r) != null)
                    {
                        myWebHeaderCollection.Remove(r);
                    }
                }
            }
            request.Referer           = lasUrl;
            request.AllowAutoRedirect = this.AutoRedirect;
            //request.KeepAlive = true;
            if (IsXMLPost)
            {
                string payload = XmlToPost;
                byte[] buff    = System.Text.Encoding.UTF8.GetBytes(payload);

                request.ContentLength = buff.Length;
                request.ContentType   = "text/plain; charset=UTF-8";

                System.IO.Stream reqStream = request.GetRequestStream();

                reqStream.Write(buff, 0, buff.Length);
            }
            else
            {
                string payload = FormElements.AssemblePostPayload();
                var    enc     = Encoding.GetEncoding("ISO-8859-1");

                byte[] buff = enc.GetBytes(payload.ToCharArray());

                request.ContentLength = buff.Length;
                request.ContentType   = "application/x-www-form-urlencoded";

                System.IO.Stream reqStream = request.GetRequestStream();

                reqStream.Write(buff, 0, buff.Length);
            }
        }
コード例 #19
0
        public void Remove_EmptyCollection_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();

            w.Remove("foo");
            Assert.Equal(0, w.Count);
            Assert.Empty(w);
            Assert.Empty(w.AllKeys);
        }
コード例 #20
0
        /// <summary>
        /// Updates the header remove header if null.
        /// </summary>
        /// <param name="headerCollection">The header collection.</param>
        /// <param name="responseHeader">The response header.</param>
        /// <param name="headerValue">The header value.</param>
        private static void UpdateHeaderOrRemoveHeaderIfNull(WebHeaderCollection headerCollection, string responseHeader, string headerValue)
        {
            if (headerValue == null)
            {
                headerCollection.Remove(responseHeader);
                return;
            }

            headerCollection[responseHeader] = headerValue;
        }
コード例 #21
0
        public void RemoveRestricted()
        {
            col = CreateRestrictedHeaders();

            try {
                col.Add("Host", "foo");
                col.Remove("Host");
                Assert.Fail("#2: should fail according to spec");
            } catch (ArgumentException) {}
        }
コード例 #22
0
        public void Remove_SetThenRemove_Success(string setName, string removeName)
        {
            WebHeaderCollection w = new WebHeaderCollection();

            w[setName] = "value";
            w.Remove(removeName);
            Assert.Equal(0, w.Count);
            Assert.Empty(w);
            Assert.Empty(w.AllKeys);
        }
コード例 #23
0
ファイル: HTTPC.cs プロジェクト: badscrew/webone
        /// <summary>
        /// Perform a GET-like request
        /// </summary>
        /// <param name="host">URL</param>
        /// <param name="cc">Cookie container</param>
        /// <param name="headers">HTTP headers</param>
        /// <param name="method">HTTP method (GET by default)</param>
        /// <param name="AllowAutoRedirect">Allow 302 redirection handling in .NET FW or not</param>
        /// <returns>Server's response.</returns>
        public HttpResponse GET(string host, CookieContainer cc, WebHeaderCollection headers, string method = "GET", bool AllowAutoRedirect = false)
        {
            try
            {
                foreach (string badhost in ConfigFile.ForceHttps)
                {
                    if (host.Substring(7).StartsWith(badhost))
                    {
                        host = "https" + host.Substring(4);
                        //Console.Write(" secure");
                        Console.WriteLine("Secure request.");
                    }
                }

                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(host);
                string         UA         = headers["User-Agent"] + " WebOne/" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                string         Accept     = headers["Accept"];
                string         Referer    = headers["Referer"];
                //undone: add other headers that cannot be passed directly to the webRequest.Headers

                foreach (string str in HeaderBanList)
                {
                    headers.Remove(str);
                }
                webRequest.Headers = headers;

                webRequest.Accept    = Accept ?? "*/*";
                webRequest.UserAgent = UA ?? UA_Mozilla;
                if (Referer != null)
                {
                    webRequest.Referer = Referer;
                }
                webRequest.Method            = method;
                webRequest.AllowAutoRedirect = true;
                webRequest.CookieContainer   = cc;
                webRequest.ProtocolVersion   = HttpVersion.Version11;
                webRequest.KeepAlive         = true;
                webRequest.AllowAutoRedirect = AllowAutoRedirect;

                webResponse = (HttpWebResponse)webRequest.GetResponse();
                return(new HttpResponse(webResponse));
            }
            catch (Exception)
            {
                throw;
            }

            /*finally
             * {
             *      if (webResponse != null)
             *              webResponse.Close();
             * }*/
        }
コード例 #24
0
        public void HttpRequestHeader_Add_Remove_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w.Add(HttpRequestHeader.Warning, "Warning1");

            Assert.Equal(1, w.Count);
            Assert.Equal("Warning1", w[HttpRequestHeader.Warning]);
            Assert.Equal("Warning", w.AllKeys[0]);

            w.Remove(HttpRequestHeader.Warning);
            Assert.Equal(0, w.Count);
        }
コード例 #25
0
ファイル: HTTPC.cs プロジェクト: ianmicheal/webone
        /// <summary>
        /// Readd non-easy headers to request
        /// </summary>
        /// <param name="Headers">Raw request header collection</param>
        /// <param name="HWR">HttpWebRequest object</param>
        void AddHeaders(WebHeaderCollection Headers, HttpWebRequest HWR)
        {
            //see https://docs.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest.headers?view=netframework-4.6#remarks
            string UA              = GetUserAgent(Headers["User-Agent"]);
            string Referer         = Headers["Referer"];
            string Accept          = Headers["Accept"];
            string ContentLength   = Headers["Content-Length"];
            string ContentType     = Headers["Content-Type"];
            string Expect          = Headers["Expect"];
            string Date            = Headers["Date"];
            string IfModifiedSince = Headers["If-Modified-Since"];
            string Range           = Headers["Range"];

            foreach (string str in HeaderBanList)
            {
                Headers.Remove(str);
            }
            HWR.Headers = Headers;

            HWR.UserAgent = UA ?? UA_Mozilla;
            if (Referer != null)
            {
                HWR.Referer = Referer;
            }
            HWR.Accept = Accept ?? "*/*";
            if (ContentLength != null)
            {
                HWR.ContentLength = long.Parse(ContentLength);
            }
            if (ContentType != null)
            {
                HWR.ContentType = ContentType;
            }
            if (Expect != null)
            {
                HWR.Expect = Expect;
            }
            if (Date != null)
            {
                HWR.Date = DateTime.Parse(Date);
            }
            DateTime IfModifiedSinceDT;

            if (IfModifiedSince != null && DateTime.TryParse(IfModifiedSince, out IfModifiedSinceDT))
            {
                HWR.IfModifiedSince = IfModifiedSinceDT;
            }
            if (Range != null)
            {
                AddRangeHeader(Range, HWR);
            }
        }
コード例 #26
0
        public void HttpRequestHeader_Add_Rmemove_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();

            w.Add(HttpRequestHeader.Warning, "Warning1");

            Assert.Equal(1, w.Count);
            Assert.Equal("Warning1", w[HttpRequestHeader.Warning]);
            Assert.Equal("Warning", w.AllKeys[0]);

            w.Remove(HttpRequestHeader.Warning);
            Assert.Equal(0, w.Count);
        }
コード例 #27
0
        public void Remove_SetTwoThenRemoveOne_Success(string setName, string removeName)
        {
            WebHeaderCollection w = new WebHeaderCollection();

            w[setName] = "value";
            w["foo"]   = "bar";
            w.Remove(removeName);
            Assert.Equal(1, w.Count);
            Assert.NotEmpty(w);
            Assert.NotEmpty(w.AllKeys);
            Assert.Equal(new[] { "foo" }, w.AllKeys);
            Assert.Equal("bar", w["foo"]);
        }
コード例 #28
0
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Remove(string key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            var countBeforeRemove = Count;

            _Collection.Remove(key);

            return(Count != countBeforeRemove);
        }
コード例 #29
0
        private void button2_Click(object sender, EventArgs e)
        {
            var item = listBox1.SelectedItem;

            if (item == null)
            {
                return;
            }

            _headers.Remove(item.ToString());
            listBox1.Items.Remove(item);
            listBox2.Items.Clear();
        }
コード例 #30
0
        public static WebHeaderCollection ToHeader(this WebHeaderCollection header, string stringifiedPayload,
                                                   DateTime dt, bool addBearer = false)
        {
            header.Remove("X-Authorization");
            header.Remove("X-Timestamp");
            header.Remove("Authorization");

            var keyByte  = Encoding.UTF8.GetBytes(Constants.Key);
            var hmacsha1 = new HMACSHA1(keyByte);

            hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(stringifiedPayload));

            header.Add("X-Timestamp", $"{dt:s}Z");
            header.Add("X-Authorization", "HMAC " + ByteToString(hmacsha1.Hash));

            if (addBearer)
            {
                header.Add("Authorization", "Bearer " + _user.AccessToken);
            }

            return(header);
        }
コード例 #31
0
    public static void Main()
    {
// <Snippet1>
        try {
            // Create a web request for "www.msn.com".
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.msn.com");

            // Get the headers associated with the request.
            WebHeaderCollection myWebHeaderCollection = myHttpWebRequest.Headers;

            // Set the Cache-Control header.
            myWebHeaderCollection.Set("Cache-Control", "no-cache");

            // Get the associated response for the above request.
            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

            // Print the headers of the request to console.
            Console.WriteLine("Print request headers after adding Cache-Control for first request:");
            printHeaders(myHttpWebRequest.Headers);

            // Remove the Cache-Control header for the new request.
            myWebHeaderCollection.Remove("Cache-Control");

            // Get the response for the new request.
            myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

            // Print the headers of the new request without the Cache-Control header.
            Console.WriteLine("Print request headers after removing Cache-Control for the new request:");
            printHeaders(myHttpWebRequest.Headers);
            myHttpWebResponse.Close();
        }
        // Catch exception if trying to remove a restricted header.
        catch (ArgumentException e) {
            Console.WriteLine("Error : Trying to remove a restricted header");
            Console.WriteLine("ArgumentException is thrown. Message is :" + e.Message);
        }
        catch (WebException e) {
            Console.WriteLine("WebException is thrown. Message is :" + e.Message);
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                Console.WriteLine("Server : {0}", ((HttpWebResponse)e.Response).Server);
            }
        }
        catch (Exception e) {
            Console.WriteLine("Exception is thrown. Message is :" + e.Message);
        }
// </Snippet1>
    }
コード例 #32
0
 public void HttpRequestHeader_Remove_Failure()
 {
     WebHeaderCollection w = new WebHeaderCollection();
     Assert.Throws<ArgumentNullException>(() => w.Remove(null));
 }
コード例 #33
0
 public void Remove_SetThenRemove_Success(string setName, string removeName)
 {
     WebHeaderCollection w = new WebHeaderCollection();
     w[setName] = "value";
     w.Remove(removeName);
     Assert.Equal(0, w.Count);
     Assert.Empty(w);
     Assert.Empty(w.AllKeys);
 }
コード例 #34
0
 public void Remove_SetTwoThenRemoveOne_Success(string setName, string removeName)
 {
     WebHeaderCollection w = new WebHeaderCollection();
     w[setName] = "value";
     w["foo"] = "bar";
     w.Remove(removeName);
     Assert.Equal(1, w.Count);
     Assert.NotEmpty(w);
     Assert.NotEmpty(w.AllKeys);
     Assert.Equal(new[] { "foo" }, w.AllKeys);
     Assert.Equal("bar", w["foo"]);
 }
コード例 #35
0
	public void TestWebHeaderCollectionRemove()
	{
		WebHeaderCollection whc = new WebHeaderCollection();
		whc.Add("some:stuff");
		whc.Remove("some");
		try
		{
			whc.Remove(null);
			Fail("Remove: failed to throw exception for null argument");
		}
		catch (ArgumentNullException)
		{
			// Ok
		}
		try
		{
			whc.Remove("[NotValidHeader?]");
			Fail("Remove: failed to throw exception for invalid header name: '[NotValidHeader?]'");
		}
		catch (ArgumentException)
		{
			// Yep...
		}
		try
		{
			whc.Remove("accept");
			Fail("Remove: failed to throw exception for restricted header 'accept'");
		}
		catch (ArgumentException)
		{
			// Still moving along...
		}
	}
コード例 #36
0
 public void Remove_EmptyCollection_Success()
 {
     WebHeaderCollection w = new WebHeaderCollection();
     w.Remove("foo");
     Assert.Equal(0, w.Count);
     Assert.Empty(w);
     Assert.Empty(w.AllKeys);
 }
コード例 #37
0
 public void Custom_RemoveBlankName_Throws()
 {
     WebHeaderCollection w = new WebHeaderCollection();
     Assert.Throws<ArgumentNullException>(() => w.Remove(""));
 }
コード例 #38
0
 public void Custom_AddThenRemove_Success()
 {
     WebHeaderCollection w = new WebHeaderCollection();
     w.Add("name", "value");
     w.Remove("name");
     Assert.Equal(0, w.Count);
 }
コード例 #39
0
 public void Custom_RemoveIllegalCharacter_Throws()
 {
     WebHeaderCollection w = new WebHeaderCollection();
     Assert.Throws<ArgumentException>(() => w.Remove("{"));
 }
コード例 #40
0
 public void Remove_IllegalCharacter_Throws()
 {
     WebHeaderCollection w = new WebHeaderCollection();
     Assert.Throws<ArgumentException>("name", () => w.Remove("{"));
 }
コード例 #41
0
 public void Remove_NullOrEmptyName_Throws(string name)
 {
     WebHeaderCollection w = new WebHeaderCollection();
     Assert.Throws<ArgumentNullException>("name", () => w.Remove(name));
 }