private void AddRequestHeaders(HttpRequestMessage request) { foreach (string requestHeaderKey in RequestHeaders.Keys) { request.Headers.Add(requestHeaderKey, RequestHeaders.Get(requestHeaderKey).ToString()); } }
private void AddRequestHeaders(HttpRequestMessage request) { foreach (var requestHeaderKey in RequestHeaders.Keys) { if (requestHeaderKey.ToLowerInvariant() == "cookie") { Cookie cookie; var cookieStr = RequestHeaders[requestHeaderKey]; if (!CookieParser.TryParse(cookieStr, request.RequestUri.Host, out cookie)) { Log.To.Sync.W(Tag, "Invalid cookie string received, {0}", new SecureLogString(cookieStr, LogMessageSensitivity.Insecure)); } else { try { CookieStore.Add(cookie); } catch (CookieException e) { var headerValue = new SecureLogString(cookieStr, LogMessageSensitivity.Insecure); Log.To.Sync.W(Tag, $"Invalid cookie string received, {headerValue}", e); } } request.Headers.Add("Cookie", CookieStore.GetCookieHeader(request.RequestUri)); continue; } request.Headers.Add(requestHeaderKey, RequestHeaders.Get(requestHeaderKey)); } }
protected override void Execute(CodeActivityContext context) { string body = string.Empty; var workflowContext = context.GetExtension <IWorkflowContext>(); if (!string.IsNullOrEmpty(RequestBody.Get <string>(context))) { body = RequestBody.Get <string>(context); } List <string> headers = new List <string>(); var requestHeaders = RequestHeaders.Get <string>(context)?.Split(';'); if (requestHeaders != null) { headers.AddRange(requestHeaders); } using (var client = new HttpClient()) { foreach (var header in headers) { var headerKeyValue = header.Split(':'); client.DefaultRequestHeaders.Add(headerKeyValue[0], headerKeyValue[1]); } var content = new StringContent(body, Encoding.UTF8, "application/json"); System.Threading.Tasks.Task <HttpResponseMessage> response = null; if (this.RequestMethod != null) { OptionSetValue value = this.RequestMethod.Get <OptionSetValue>(context); if (value != null && value.Value != 0) { response = SendRequest(context, client, value.Value, content); } } if (response != null) { response.Result.EnsureSuccessStatusCode(); StringBuilder delimitedHeaders = new StringBuilder(); foreach (var header in response.Result.Headers) { if (delimitedHeaders.Length > 0) { delimitedHeaders.Append(";"); } delimitedHeaders.Append($"{header.Key}:{header.Value}"); } ResponseHeaders.Set(context, delimitedHeaders.ToString()); var responseString = response.Result.Content.ReadAsStringAsync(); ResponseBody.Set(context, responseString.Result); } } }
public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { RequestHeaders headers = context.HttpContext.Request.GetTypedHeaders(); AuthenticationHeaderValue authentication = headers.Get <AuthenticationHeaderValue>("DiagnosticServicesAuthorization"); if (authentication == null) { context.Result = Unauthorized("Authentication is required."); return; } if (authentication.Scheme != "Bearer") { context.Result = Forbidden("'Bearer' is the only supported authorization scheme."); return; } string token = authentication.Parameter; if (string.IsNullOrEmpty(token)) { context.Result = Forbidden("Token is missing."); return; } try { TokenContract tokenContract = _tokenService.ValidateSecurityToken(token); // TODO: Validate it contains the expected app Id too. if (!tokenContract.PermissionLevel.HasFlag(_permissionLevel)) { context.Result = Forbidden($"Insufficient permission level: {tokenContract.PermissionLevel}"); return; } context.HttpContext.Features.Set <ProfilerContext>(new ProfilerContext() { AppId = tokenContract.AppId }); } catch (SecurityTokenExpiredException ex) { _logger.LogError(ex, "Token expired."); context.Result = Forbidden(ex.Message); } catch (Exception ex) { _logger.LogError(ex, "Token validation error"); context.Result = Forbidden(ex.Message); } // TODO: Is async op needed? await Task.CompletedTask; }
/// <summary> /// 获取SessionId /// </summary> /// <param name="session_token"></param> /// <returns></returns> public static String GetSessionId(string session_token) { IHttpContextAccessor hca = GlobalContextUtils.ServiceProvider.GetRequiredService <IHttpContextAccessor>(); RequestHeaders requestHeaders = hca?.HttpContext?.Request.GetTypedHeaders(); string sessionToken = requestHeaders?.Get <string>(session_token); if (!String.IsNullOrEmpty(sessionToken)) { return(sessionToken); } return(hca?.HttpContext?.Session.Id); }
public override string ToString() { string headers = string.Empty; foreach (string key in RequestHeaders.AllKeys) { headers += key + " " + RequestHeaders.Get(key) + "; "; } return(string.Format( "URL:{0}\r\n Method:{1}\r\n StatusCode:{2}\r\n Timeout:{3}\r\n ReadWriteTimeout:{4}\r\n Headers:{5}", RequestUrl, Method, StatusCode, Timeout, ReadWriteTimeout, headers)); }
public void Send(string queryString) { _client = new TcpClient(_host, _port) { ReceiveTimeout = 5000, NoDelay = true }; var headerString = new StringBuilder(); headerString.AppendFormat("GET {0} HTTP/1.1\nHost: {1}\n", queryString, _host); RequestHeaders["Connection"] = "close"; foreach (var headerName in RequestHeaders.AllKeys) { headerString.AppendFormat("{0}: {1}\n", headerName, RequestHeaders.Get(headerName)); } Stream = new NonClosingStream(_client.GetStream()); var queryHeaders = Encoding.ASCII.GetBytes(headerString.ToString() + '\n'); Stream.Write(queryHeaders, 0, queryHeaders.Length); // No using statement, we don't want the stream to be disposed var textReader = new UnbufferedStreamReader(Stream); foreach (var line in textReader.ReadUntil("\r\n\r\n") .Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries) .Where(line => !string.IsNullOrEmpty(line))) { if (line.Contains(':')) { ResponseHeaders.Add(line); } else if (line.IndexOf("HTTP/", StringComparison.Ordinal) == 0) { StatusCode = int.Parse(line.Substring(9, 3)); } } if (!LogRequest) { return; } Console.WriteLine("{2}: http://{0}{1}", _host, queryString, StatusCode); Console.WriteLine(ResponseHeaders.ToString()); }
public string IfMatch() { string ifMatch = RequestHeaders.Get("If-Match"); if (ifMatch == null) { return(null); } // Value of If-Match is an ETag, so have to trim the quotes around it: if (ifMatch.Length > 2 && ifMatch.StartsWith("\"") && ifMatch.EndsWith("\"")) { return(ifMatch.Trim('"')); } return(null); }
List <string> IServiceConfiguration.GetRequestHeaders() => RequestHeaders.Get();
public bool ExplicitlyAcceptsType(string type) { string accept = RequestHeaders.Get("Accept"); return(accept != null && accept.Contains(type)); }
public override bool CacheWithEtag(string etag) { etag = String.Format("\"{0}\"", etag); _httpContext.Response.Headers["Etag"] = etag; return(etag.Equals(RequestHeaders.Get("If-None-Match"))); }