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


C# HttpResponseMessage类代码示例

本文整理汇总了C#中HttpResponseMessage的典型用法代码示例。如果您正苦于以下问题:C# HttpResponseMessage类的具体用法?C# HttpResponseMessage怎么用?C# HttpResponseMessage使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: SendGetRequest

		static public async Task<string> SendGetRequest ( string address )
		{
			var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter ();
			httpFilter.CacheControl.ReadBehavior =
				Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
			httpClient = new HttpClient ( httpFilter );
			response = new HttpResponseMessage ();
			string responseText = "";

			//check address
			Uri resourceUri;
			if ( !Uri.TryCreate ( address.Trim () , UriKind.Absolute , out resourceUri ) )
			{
				return "Invalid URI, please re-enter a valid URI";
			}
			if ( resourceUri.Scheme != "http" && resourceUri.Scheme != "https" )
			{
				return "Only 'http' and 'https' schemes supported. Please re-enter URI";
			}

			//get
			try
			{
				response = await httpClient.GetAsync ( resourceUri );
				response.EnsureSuccessStatusCode ();
				responseText = await response.Content.ReadAsStringAsync ();
			}
			catch ( Exception ex )
			{
				// Need to convert int HResult to hex string
				responseText = "Error = " + ex.HResult.ToString ( "X" ) + "  Message: " + ex.Message;
			}
			httpClient.Dispose ();
			return responseText;
		}
开发者ID:tranchikhang,项目名称:BookShare,代码行数:35,代码来源:RestAPI.cs

示例2: SendAsync

    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Method == HttpMethod.Get && request.RequestUri.Segments.Last() == "authtoken")
        {
            string querystring = request.RequestUri.Query.Substring(1);
            string[] queryParams = querystring.Split(new[] { '&' });

            var queryStringParams = request.RequestUri.ParseQueryString();
            if (queryStringParams.Count > 0)
            {
                string code = queryParams.Where(p => p.StartsWith("code")).First().Split(new[] { '=' })[1];

                return Task.Factory.StartNew(
                    () =>
                    {
                        string accessToken = this.GetFacebookAccessToken(code, request);
                        string username = GetFacebookUsername(accessToken);

                        var ticket = new FormsAuthenticationTicket(username, false, 60);
                        string s = FormsAuthentication.Encrypt(ticket);

                        var response = new HttpResponseMessage();
                        response.Headers.Add("Set-Cookie", string.Format("ticket={0}; path=/", s));

                        var responseContentBuilder = new StringBuilder();
                        responseContentBuilder.AppendLine("<html>");
                        responseContentBuilder.AppendLine("   <head>");
                        responseContentBuilder.AppendLine("      <title>Login Callback</title>");
                        responseContentBuilder.AppendLine("   </head>");
                        responseContentBuilder.AppendLine("   <body>");
                        responseContentBuilder.AppendLine("      <script type=\"text/javascript\">");
                        responseContentBuilder.AppendLine(
                            "         if(window.opener){");

                        if (queryStringParams["callback"] != null)
                        {
                            responseContentBuilder.AppendLine(queryStringParams["callback"] + "();");
                        }

                        responseContentBuilder.AppendLine("            window.close()';");
                        responseContentBuilder.AppendLine("         }");
                        responseContentBuilder.AppendLine("      </script>");
                        responseContentBuilder.AppendLine("   </body>");
                        responseContentBuilder.AppendLine("</html>");

                        response.Content = new StringContent(responseContentBuilder.ToString());
                        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                        response.Headers.CacheControl = new CacheControlHeaderValue { NoCache = true };

                        return response;
                    });
            }

            return Task.Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.InternalServerError));
        }

        return base.SendAsync(request, cancellationToken);
    }
开发者ID:Tinytoot,项目名称:TeamThing,代码行数:59,代码来源:OAuthMessageHandler.cs

示例3: HttpContext

 /// <summary>
 /// Initializes a new instance of the <see cref="HttpContext" /> class.
 /// </summary>
 public HttpContext()
 {
     Response = new HttpResponseMessage();
     Items = new KeyValuePair<string, object>();
     Application = new KeyValuePair<string, object>();
     Session = new KeyValuePair<string, object>();
 }
开发者ID:microcompiler,项目名称:microserver.uwp,代码行数:10,代码来源:HttpContext.cs

示例4: HttpException

 public HttpException(HttpResponseMessage response, COMException innerException, string message = null)
     : this(GetResponseExceptionMessage(response, message), innerException)
 {
     HResult = innerException.HResult;
     _request = response?.RequestMessage;
     _response = response;
 }
开发者ID:ali-hk,项目名称:Toolkit,代码行数:7,代码来源:HttpException.cs

示例5: HttpGets

        public static async Task<string> HttpGets(string uri)
        {


            if (Config.IsNetWork)
            {
                NotifyControl notify = new NotifyControl();
                notify.Text = "亲,努力加载中...";
              
                notify.Show();
                using (HttpClient httpClient = new HttpClient())
                {
                    try
                    {
                        HttpResponseMessage response = new HttpResponseMessage();
                        response = await httpClient.GetAsync(new Uri(uri, UriKind.Absolute));
                        responseString = await response.Content.ReadAsStringAsync();
                        notify.Hide();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message.ToString());
                    }
                    
                  
                }
              
            }
            return responseString;
                
           

        }
开发者ID:x01673,项目名称:dreaming,代码行数:33,代码来源:HttpGet.cs

示例6: Get

 public IHttpActionResult Get([FromUri] string to_sign)
 {
     var content = new StringContent(SignData(to_sign));
     content.Headers.ContentType = new MediaTypeHeaderValue(MediaTypeNames.Text.Plain);
     var response = new HttpResponseMessage(HttpStatusCode.OK) {Content = content};
     return ResponseMessage(response);
 }
开发者ID:robert-maftei93,项目名称:EvaporateJS,代码行数:7,代码来源:SigningExample.cs

示例7: CreateResponse

        private HttpResponseMessage CreateResponse(HttpRequestMessage request, HttpWebResponse httpResponse)
        {
            HttpResponseMessage response;
            response = new HttpResponseMessage(httpResponse.StatusCode);
            response.Request = request;
            response.CopyHeadersFrom(httpResponse.Headers);
            response.StatusCode = httpResponse.StatusCode;

            MemoryStream memory;
            var contentLength = response.Headers[HttpResponseHeader.ContentLength];
            int contentIntLength;
            if (int.TryParse(contentLength, out contentIntLength))
            {
                memory = new MemoryStream(contentIntLength);
            }
            else
            {
                memory = new MemoryStream();
            }

            var responseStream = httpResponse.GetResponseStream();
            responseStream.CopyTo(memory);
            memory.Seek(0L, SeekOrigin.Begin);

            response.Content = new HttpContent(memory);
            return response;
        }
开发者ID:biapar,项目名称:ovhapicil,代码行数:27,代码来源:HttpClient.cs

示例8: WinRtHttpClientWebStreamResponse

        public WinRtHttpClientWebStreamResponse(HttpResponseMessage response)
        {
            if (null == response)
                throw new ArgumentNullException(nameof(response));

            _response = response;
        }
开发者ID:henricj,项目名称:phonesm,代码行数:7,代码来源:WinRtHttpClientWebStreamResponse.cs

示例9: Headers_ReadProperty_HeaderCollectionInitialized

 public void Headers_ReadProperty_HeaderCollectionInitialized()
 {
     using (var rm = new HttpResponseMessage())
     {
         Assert.NotNull(rm.Headers);
     }
 }
开发者ID:dotnet,项目名称:corefx,代码行数:7,代码来源:HttpResponseMessageTest.cs

示例10: ThrowIfErrorAsync

        public static async Task ThrowIfErrorAsync(HttpResponseMessage msg)
        {
            const int TooManyRequests = 429;

            // TODO: research proper handling of 304

            if ((int)msg.StatusCode < 400) return;

            switch (msg.StatusCode)
            {
                case HttpStatusCode.Unauthorized:
                    await HandleUnauthorizedAsync(msg).ConfigureAwait(false);
                    break;
                default:
                    switch ((int)msg.StatusCode)
	                {
                        case TooManyRequests:
                            await HandleTooManyRequestsAsync(msg).ConfigureAwait(false);
                            break;
		                default:
                            await HandleGenericErrorAsync(msg).ConfigureAwait(false);
                            break;
	                }
                    break;
            } 
        }
开发者ID:prog-moh,项目名称:LinqToTwitter,代码行数:26,代码来源:TwitterErrorHandler.cs

示例11: ExecuteAsync

 public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
 {
     HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
     response.Content = new StringContent(Content);
     response.RequestMessage = Request;
     return Task.FromResult(response);
 }
开发者ID:chimpinano,项目名称:generator-webapi-owin-jwt-aspnet-identity,代码行数:7,代码来源:_apiglobalexceptionhandler.cs

示例12: HttpGet

        public static async Task<string> HttpGet(string uri)
        {


            if (Config.IsNetWork)
            {
                NotifyControl notify = new NotifyControl();
                notify.Text = "亲,努力加载中...";
                notify.Show();
             
                var _filter = new HttpBaseProtocolFilter();
                using (HttpClient httpClient = new HttpClient(_filter))
                {

                    _filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
                    HttpResponseMessage response = new HttpResponseMessage();
                    response = await httpClient.GetAsync(new Uri(uri, UriKind.Absolute));
                    responseString = await response.Content.ReadAsStringAsync();
                    notify.Hide();

                }

            }
            return responseString;



        }
开发者ID:x01673,项目名称:dreaming,代码行数:28,代码来源:HttpGetNoCache.cs

示例13: SendAsync

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // if request is local, just serve it without https
        object httpContextBaseObject;
        if (request.Properties.TryGetValue("MS_HttpContext", out httpContextBaseObject))
        {
            var httpContextBase = httpContextBaseObject as HttpContextBase;

            if (httpContextBase != null && httpContextBase.Request.IsLocal)
            {
                return base.SendAsync(request, cancellationToken);
            }
        }

        // if request is remote, enforce https
        if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            return Task<HttpResponseMessage>.Factory.StartNew(
                () =>
                {
                    var response = new HttpResponseMessage(HttpStatusCode.Forbidden)
                    {
                        Content = new StringContent("HTTPS Required")
                    };

                    return response;
                });
        }

        return base.SendAsync(request, cancellationToken);
    }
开发者ID:jmstefans,项目名称:FlavorOfTheMonth,代码行数:31,代码来源:EnforceHttpsHandler.cs

示例14: HandleResult

		public async static Task<CallRet> HandleResult(HttpResponseMessage response)
        {
            var statusCode = response.StatusCode;
            var msg = await response.Content.ReadAsStringAsync();

            return new CallRet(statusCode, msg);
        }
开发者ID:liqinghuang,项目名称:QiniuUWP,代码行数:7,代码来源:FileOpClient.cs

示例15: ToString_UseBothNoParameterAndSetParameter_AllSerializedCorrectly

        public void ToString_UseBothNoParameterAndSetParameter_AllSerializedCorrectly()
        {
            using (HttpResponseMessage response = new HttpResponseMessage())
            {
                string input = string.Empty;

                AuthenticationHeaderValue auth = new AuthenticationHeaderValue("Digest",
                    "qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"");

                Assert.Equal(
                    "Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"",
                    auth.ToString());
                response.Headers.ProxyAuthenticate.Add(auth);
                input += auth.ToString();

                auth = new AuthenticationHeaderValue("Negotiate");
                Assert.Equal("Negotiate", auth.ToString());
                response.Headers.ProxyAuthenticate.Add(auth);
                input += ", " + auth.ToString();

                auth = new AuthenticationHeaderValue("Custom", ""); // empty string should be treated like 'null'.
                Assert.Equal("Custom", auth.ToString());
                response.Headers.ProxyAuthenticate.Add(auth);
                input += ", " + auth.ToString();

                string result = response.Headers.ProxyAuthenticate.ToString();
                Assert.Equal(input, result);
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:29,代码来源:AuthenticationHeaderValueTest.cs


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