当前位置: 首页>>代码示例>>C#>>正文


C# HttpMethod.ToString方法代码示例

本文整理汇总了C#中HttpMethod.ToString方法的典型用法代码示例。如果您正苦于以下问题:C# HttpMethod.ToString方法的具体用法?C# HttpMethod.ToString怎么用?C# HttpMethod.ToString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在HttpMethod的用法示例。


在下文中一共展示了HttpMethod.ToString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ToString_ReturnName_Success

        public void ToString_ReturnName_Success()
        {
            const string methodName = "get";

            var method = new HttpMethod(methodName);
        
            Assert.AreEqual(methodName.ToUpper(), method.ToString());
            Assert.AreEqual(method.Name, method.ToString());
        }
开发者ID:alekseysukharev,项目名称:proxy,代码行数:9,代码来源:HttpMethodTests.cs

示例2: RetrieveResponseTextFromUrl

        private static string RetrieveResponseTextFromUrl(HttpMethod httpMethod, string url, out HttpResponseMessage httpResponseMessage, List<KeyValuePair<string, string[]>> additionalHeaders)
        {
            Trace.WriteLine(string.Format("Accessing the URL : {0}", url));
            HttpClient client = new HttpClient();

            if (additionalHeaders != null)
            {
                additionalHeaders.ForEach((kvp) =>
                {
                    string inputHeaderValue = string.Join(", ", kvp.Value);
                    Trace.WriteLine(string.Format("Adding additional input HTTP header : {0} with values : {1}", kvp.Key, inputHeaderValue));
                    client.DefaultRequestHeaders.Add(kvp.Key, string.Join(", ", inputHeaderValue));
                });
            }

            switch (httpMethod.ToString())
            {
                case "GET":
                    httpResponseMessage = client.GetAsync(url).Result;
                    break;
                case "HEAD":
                    var requestMessage = new HttpRequestMessage(HttpMethod.Head, url);
                    httpResponseMessage = client.SendAsync(requestMessage).Result;
                    break;
                case "POST":
                    httpResponseMessage = client.PostAsync(url, new StringContent("Test body")).Result;
                    break;
                default:
                    throw new NotImplementedException(string.Format("Utility code not implemented for this Http method {0}", httpMethod));
            }

            string responseText = httpResponseMessage.Content.ReadAsStringAsync().Result;
            Trace.WriteLine(string.Format("Response Text: {0}", responseText));
            return responseText;
        }
开发者ID:Xamarui,项目名称:Katana,代码行数:35,代码来源:HttpClientUtility.cs

示例3: HttpWorker

        public HttpWorker(Uri uri, HttpMethod httpMethod = HttpMethod.Get, Dictionary<string, string> headers = null, byte[] data = null)
        {
            _buffer = new byte[8192];
            _bufferIndex = 0;
            _read = 0;
            _responseType = ResponseType.Unknown;
            _uri = uri;
            IPAddress ip;
            var headersString = string.Empty;
            var contentLength = data != null ? data.Length : 0;

            if (headers != null && headers.Any())
                headersString = string.Concat(headers.Select(h => "\r\n" + h.Key.Trim() + ": " + h.Value.Trim()));

            if (_uri.HostNameType == UriHostNameType.Dns)
            {
                var host = Dns.GetHostEntry(_uri.Host);
                ip = host.AddressList.First(i => i.AddressFamily == AddressFamily.InterNetwork);
            }
            else
            {
                ip = IPAddress.Parse(_uri.Host);
            }

            _endPoint = new IPEndPoint(ip, _uri.Port);
            _request = Encoding.UTF8.GetBytes($"{httpMethod.ToString().ToUpper()} {_uri.PathAndQuery} HTTP/1.1\r\nAccept-Encoding: gzip, deflate, sdch\r\nHost: {_uri.Host}\r\nContent-Length: {contentLength}{headersString}\r\n\r\n");

            if (data == null)
                return;

            var tmpRequest = new byte[_request.Length + data.Length];
            Buffer.BlockCopy(_request, 0, tmpRequest, 0, _request.Length);
            Buffer.BlockCopy(data, 0, tmpRequest, _request.Length, data.Length);
            _request = tmpRequest;
        }
开发者ID:evest,项目名称:Netling,代码行数:35,代码来源:HttpWorker.cs

示例4: VerifyUnauthorizedErrorReturned

        public static async Task VerifyUnauthorizedErrorReturned(HttpClient client, HttpMethod method, string requestUri)
        {
            var response = await client.SendAsync(new HttpRequestMessage(method, requestUri));

            response.StatusCode.Should().Be(HttpStatusCode.Unauthorized, "{0} command at {1} should be unauthorized.", method.ToString(), requestUri);
            response.Headers.WwwAuthenticate.Should().ContainSingle(x => x.Scheme == "Basic");
        }
开发者ID:swharr,项目名称:API-Examples,代码行数:7,代码来源:TestHelper.cs

示例5: JSONResponse

      internal static JObject JSONResponse( string url, HttpMethod method, AuthenticationResult authResult, string apiPayload = "" )
      {
         HttpWebRequest webClientRequest;
         webClientRequest = WebRequest.CreateHttp( new Uri( url ) );
         webClientRequest.Method = method.ToString();
         webClientRequest.Headers.Add( "Authorization", authResult.CreateAuthorizationHeader() );
         if ( method != HttpMethod.Get )
         {
            using ( var writer = new StreamWriter( webClientRequest.GetRequestStream() ) )
            {
               writer.Write( apiPayload );

            }
         }
         WebResponse response;
         JObject jsonResponse = null;
         try
         {
            response = webClientRequest.GetResponse();
         }
         catch ( WebException webEx )
         {
            response = webEx.Response;
         }
         using ( var reader = new StreamReader( response.GetResponseStream() ) )
         {
            jsonResponse = JObject.Parse( reader.ReadToEnd() );
         }
         return jsonResponse;
      }
开发者ID:rjmporter,项目名称:TscOdfbUtility,代码行数:30,代码来源:Program.cs

示例6: WebRequest

 /// <summary>
 /// Webs the request.
 /// </summary>
 /// <param name="method">The method.</param>
 /// <param name="url">The URL.</param>
 /// <param name="postData">The post data.</param>
 /// <returns></returns>
 public string WebRequest(HttpMethod method, string url, string postData)
 {
     this.Message = string.Empty;
     HttpWebRequest webRequest = null;
     StreamWriter requestWriter = null;
     string responseData = "";
     webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
     webRequest.Method = method.ToString();
     webRequest.ServicePoint.Expect100Continue = false;
     if (method == HttpMethod.POST)
     {
         webRequest.ContentType = "application/x-www-form-urlencoded";
         requestWriter = new StreamWriter(webRequest.GetRequestStream());
         try
         {
             requestWriter.Write(postData);
         }
         catch (Exception ex)
         {
             this.Message = ex.Message;
         }
         finally
         {
             requestWriter.Close();
             requestWriter = null;
         }
     }
     responseData = GetWebResponse(webRequest);
     webRequest = null;
     return responseData;
 }
开发者ID:JPomichael,项目名称:IPOW,代码行数:38,代码来源:WebHttpHelper.cs

示例7: GetContent

        public static string GetContent(string contentType, HttpMethod method, string urlPath)
        {
            Uri url = new Uri(urlPath);
            string content = null;
            string statusCode = string.Empty;

            try {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Accept = contentType;
                request.Method = method.ToString();

                WebResponse webResponse = request.GetResponse();
                StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                if (webResponse.ContentLength > 0) {
                    switch (contentType) {
                        case "text/javascript":
                            content = sr.ReadToEnd();
                            break;

                        case "application/xml":
                             break;
                    }
                }
                else {
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    if (response.StatusCode != HttpStatusCode.NoContent) {

                    }
                }
            }
            catch (WebException we) {
                throw we;
            }
            return content;
        }
开发者ID:nickfloyd,项目名称:forrst-dotnet,代码行数:35,代码来源:HttpRequest.cs

示例8: GenerateRequest

        public HttpWebRequest GenerateRequest(ICommandRequest request, string userId, HttpMethod requestMethod)
        {
            Validator.ValidateObject(request, new ValidationContext(request, null, null), true);

            var webRequest = (HttpWebRequest) WebRequest.Create(request.Resource);
            webRequest.Method = requestMethod.ToString();
            webRequest.ContentType = "application/octet-stream";

            var requestType = request.GetType();
            var properties = requestType.GetProperties(PropertyFilters)
                .Where(
                    p =>
                    (p.GetValue(request, null) != null) &&
                    (!string.IsNullOrWhiteSpace(p.GetValue(request, null).ToString())))
                .Where(p => p.GetCustomAttributes(false).OfType<HeaderAttribute>().Where(h => h.Serialise).Any())
                .Select(p => new
                                 {
                                     Name = p.GetCustomAttributes(false).OfType<HeaderAttribute>().Select(h => h.Name).First(),
                                     Value = p.GetValue(request, null).ToString()
                                 }).ToList();

            properties.Add(new { Name = "x-emc-date", Value = DateTime.UtcNow.ToString("r") });
            properties.Add(new { Name = "x-emc-uid", Value = userId });

            foreach (var property in properties)
            {
                webRequest.Headers.Add(property.Name, property.Value);
            }

            return webRequest;
        }
开发者ID:stephengodbold,项目名称:ninefold-dotnet-api,代码行数:31,代码来源:StorageCommandBuilder.cs

示例9: GenerateSignature

        static string GenerateSignature(string consumerSecret, Uri uri, HttpMethod method, Token token, IEnumerable<KeyValuePair<string, string>> parameters)
        {
            if (ComputeHash == null)
            {
                throw new InvalidOperationException("ComputeHash is null, must initialize before call OAuthUtility.HashFunction = /* your computeHash code */ at once.");
            }

            var hmacKeyBase = consumerSecret.UrlEncode() + "&" + ((token == null) ? "" : token.Secret).UrlEncode();

            // escaped => unescaped[]
            var queryParams = Utility.ParseQueryString(uri.GetComponents(UriComponents.Query | UriComponents.KeepDelimiter, UriFormat.UriEscaped));

            var stringParameter = parameters
                .Where(x => x.Key.ToLower() != "realm")
                .Concat(queryParams)
                .Select(p => new { Key = p.Key.UrlEncode(), Value = p.Value.UrlEncode() })
                .OrderBy(p => p.Key, StringComparer.Ordinal)
                .ThenBy(p => p.Value, StringComparer.Ordinal)
                .Select(p => p.Key + "=" + p.Value)
                .ToString("&");
            var signatureBase = method.ToString() +
                "&" + uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped).UrlEncode() +
                "&" + stringParameter.UrlEncode();

            var hash = ComputeHash(Encoding.UTF8.GetBytes(hmacKeyBase), Encoding.UTF8.GetBytes(signatureBase));
            return Convert.ToBase64String(hash).UrlEncode();
        }
开发者ID:llenroc,项目名称:AsyncOAuth,代码行数:27,代码来源:OAuthUtility.cs

示例10: CreateRequest

 private static IHttpRequest CreateRequest(string uri, HttpMethod method)
 {
     var mockRequest = new Mock<IHttpRequest>();
     mockRequest.Setup(r => r.Method).Returns(method.ToString());
     mockRequest.Setup(r => r.Uri).Returns(new Uri("http://localhost" + uri));
     return mockRequest.Object;
 }
开发者ID:gudmundurh,项目名称:Frank,代码行数:7,代码来源:RouteTest.cs

示例11: Create

        /// <summary>
        /// The Redirect element directs the call to another InboundXML document.
        /// </summary>
        /// <param name="url">Url to another InboundXML document</param>
        /// <param name="method">Method used to request the InboundXML doucment the call is being redirected to.</param>
        /// <returns></returns>
        public static Redirect Create(string url, HttpMethod? method)
        {
            var redirect = new Redirect();

            redirect.Url = url;
            redirect.Method = method == null ? null : method.ToString();

            return redirect;
        }
开发者ID:TelAPI,项目名称:telapi-dotnet,代码行数:15,代码来源:Redirect.cs

示例12: RequestHeaderParserAcceptsStandardMethods

        public void RequestHeaderParserAcceptsStandardMethods(HttpMethod method)
        {
            byte[] data = CreateBuffer(method.ToString(), "/", "HTTP/1.1", ParserData.ValidHeaders);

            for (var cnt = 1; cnt <= data.Length; cnt++)
            {
                HttpUnsortedRequest result = new HttpUnsortedRequest();
                HttpRequestHeaderParser parser = new HttpRequestHeaderParser(result);
                Assert.NotNull(parser);

                int totalBytesConsumed = 0;
                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);
                Assert.Equal(ParserState.Done, state);
                Assert.Equal(data.Length, totalBytesConsumed);

                ValidateResult(result, method.ToString(), "/", new Version("1.1"), ParserData.ValidHeaders);
            }
        }
开发者ID:Vizzini,项目名称:aspnetwebstack,代码行数:18,代码来源:HttpRequestHeaderParserTests.cs

示例13: MakeApiUploadStringCall

 // Basis for PUT, POST, and DELETE
 private string MakeApiUploadStringCall(HttpMethod httpMethod, string apiEndpoint, Dictionary<string, string> parameters = null, string jsonData = null)
 {
     var url = this.urlGenerator.GenerateRequestUrl(httpMethod, apiEndpoint, parameters);
     using (var webClient = new WebClient())
     {
         webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
         return webClient.UploadString(url, httpMethod.ToString().ToUpper(), jsonData ?? String.Empty);
     }
 }
开发者ID:T-REX-XP,项目名称:SharpCommerce,代码行数:10,代码来源:WoocommerceApiDriver.cs

示例14: Create

        /// <summary>
        /// The Sip element is nested within the Dial element, and is used to call to sip addresses.
        /// </summary>
        /// <param name="sipAddress">Sip address</param>
        /// <param name="sendDigits">Specifies which DTFM tones to play to the called party. w indicates a half second pause.</param>
        /// <param name="url">URL that the called party can be directed to before the call beings.</param>
        /// <param name="method">method used to request the url.</param>
        /// <returns></returns>
        public static Sip Create(string sipAddress, string sendDigits, string url, HttpMethod? method)
        {
            Sip sip = new Sip();

            sip.SipAddress = sipAddress;
            sip.SendDigits = sendDigits;
            sip.Url = url;
            sip.Method = method == null ? null : method.ToString();

            return sip;
        }
开发者ID:TelAPI,项目名称:telapi-dotnet,代码行数:19,代码来源:Sip.cs

示例15: Create

        /// <summary>
        /// It can be used to send DTFM tones or redirect to InboundXML
        /// </summary>
        /// <param name="number">Number</param>
        /// <param name="sendDigits">Specifies which DTFM tones to play to the called party. w indicates a half second pause.</param>
        /// <param name="url">URL that the called party can be directed to before the call beings.</param>
        /// <param name="method">method used to request the url.</param>
        /// <returns></returns>
        public static Number Create(string number, string sendDigits, string url, HttpMethod? method)
        {
            var num = new Number();

            num.Value = number;
            num.SendDigits = sendDigits;
            num.Url = url;
            num.Method = method == null ? null : method.ToString();

            return num;
        }
开发者ID:TelAPI,项目名称:telapi-dotnet,代码行数:19,代码来源:Number.cs


注:本文中的HttpMethod.ToString方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。