public NameValueCollection ToNameValueCollection(IHeaderDictionary dict) { var nameValueCollection = new NameValueCollection(); foreach (var kvp in dict) { string value = null; if (!string.IsNullOrEmpty(kvp.Value)) { value = kvp.Value.ToString(); } nameValueCollection.Add(kvp.Key.ToString(), value); } return nameValueCollection; }
/// <summary> /// Adopts protocol terms into owin environment. /// </summary> private void PopulateEnvironment() { var headers = _protocolStream.Headers; _owinContext = new OwinContext(); _responseHeaders = _owinContext.Response.Headers; var headersAsDict = headers.ToDictionary(header => header.Key, header => new[] { header.Value }, StringComparer.OrdinalIgnoreCase); _owinContext.Environment[CommonOwinKeys.RequestHeaders] = headersAsDict; var owinRequest = _owinContext.Request; var owinResponse = _owinContext.Response; owinRequest.Method = headers.GetValue(CommonHeaders.Method); var path = headers.GetValue(CommonHeaders.Path); owinRequest.Path = path.StartsWith(@"/") ? new PathString(path) : new PathString(@"/" + path); owinRequest.CallCancelled = CancellationToken.None; owinRequest.Host = new HostString(headers.GetValue(CommonHeaders.Authority)); owinRequest.PathBase = PathString.Empty; owinRequest.QueryString = QueryString.Empty; owinRequest.Body = Stream.Null; owinRequest.Protocol = Protocols.Http2; owinRequest.Scheme = headers.GetValue(CommonHeaders.Scheme) == Uri.UriSchemeHttp ? Uri.UriSchemeHttp : Uri.UriSchemeHttps; owinResponse.Body = new ResponseStream(_protocolStream, StartResponse); }
/// <summary> /// Create a new wrapper /// </summary> /// <param name="headers"></param> public ResponseCookieCollection(IHeaderDictionary headers) { if (headers == null) { throw new ArgumentNullException("headers"); } Headers = headers; }
/// <summary> /// Create a new wrapper /// </summary> /// <param name="headers"></param> public ResponseCookies(IHeaderDictionary headers) { if (headers == null) { throw new ArgumentNullException(nameof(headers)); } Headers = headers; }
internal static IDictionary<string, string[]> MakeDictionaryStringArray(IHeaderDictionary dictionary) { var wrapper = dictionary as DictionaryStringValuesWrapper; if (wrapper != null) { return wrapper.Inner; } return new DictionaryStringArrayWrapper(dictionary); }
/// <summary> /// Gets If-Modified-Since time header from headers collection. /// </summary> /// <param name="headers">The headers.</param> /// <returns></returns> public static DateTime? GetIfModifiedSinceTime(IHeaderDictionary headers) { DateTime? ifModifiedSinceTime = null; if (headers.ContainsKey("If-Modified-Since")) ifModifiedSinceTime = DateTime.ParseExact(headers["If-Modified-Since"], "r", CultureInfo.InvariantCulture); return ifModifiedSinceTime; }
public static StringValues GetHeaderUnmodified(IHeaderDictionary headers, string key) { if (headers == null) { throw new ArgumentNullException(nameof(headers)); } StringValues values; return headers.TryGetValue(key, out values) ? values : StringValues.Empty; }
/// <summary> /// Create a new wrapper. /// </summary> /// <param name="headers">The <see cref="IHeaderDictionary"/> for the response.</param> /// <param name="builderPool">The <see cref="ObjectPool{T}"/>, if available.</param> public ResponseCookies(IHeaderDictionary headers, ObjectPool<StringBuilder> builderPool) { if (headers == null) { throw new ArgumentNullException(nameof(headers)); } Headers = headers; _builderPool = builderPool; }
public ODataMessageWrapper(Stream stream, IHeaderDictionary headers, IDictionary<string, string> contentIdMapping) { _stream = stream; if (headers != null) { _headers = headers.ToDictionary(kvp => kvp.Key, kvp => String.Join(";", kvp.Value)); } else { _headers = new Dictionary<string, string>(); } _contentIdMapping = contentIdMapping ?? new Dictionary<string, string>(); }
private static ResponseCompressions GetCompression(IHeaderDictionary headers) { if (!headers.ContainsKey(AcceptEncodingHeader)) return ResponseCompressions.None; var encodingsAccepted = headers[AcceptEncodingHeader] .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(s => s.Trim()); var firstEncoding = encodingsAccepted .FirstOrDefault(e => _supportedCompressions.ContainsKey(e)); ; return _supportedCompressions[firstEncoding ?? string.Empty]; }
public static void SetHeaderJoined(IHeaderDictionary headers, string key, StringValues value) { if (headers == null) { throw new ArgumentNullException(nameof(headers)); } if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException(nameof(key)); } if (StringValues.IsNullOrEmpty(value)) { headers.Remove(key); } else { headers[key] = string.Join(",", value.Select((s) => QuoteIfNeeded(s))); } }
private static bool ContainsCspHeader(IHeaderDictionary headers) { return headers.ContainsKey(HeaderConstants.ContentSecurityPolicyReportOnly); }
private static IOwinRequest CreateStubRequest(IHeaderDictionary headers) { Mock<IOwinRequest> mock = new Mock<IOwinRequest>(MockBehavior.Strict); mock.SetupGet(r => r.Headers).Returns(headers); return mock.Object; }
public static string Allow(this IHeaderDictionary headers) { return(nameof(Allow)); }
/// <summary> /// Diagnostic event handler method for 'Microsoft.AspNetCore.Hosting.BeginRequest' event. This is from 1.XX runtime. /// </summary> /// <param name="httpContext">HttpContext is used to retrieve information about the Request and Response.</param> /// <param name="timestamp">Used to set the request start property.</param> public void OnBeginRequest(HttpContext httpContext, long timestamp) { if (this.client.IsEnabled() && this.aspNetCoreMajorVersion == AspNetCoreMajorVersion.One) { // It's possible to host multiple apps (ASP.NET Core or generic hosts) in the same process // Each of this apps has it's own HostingDiagnosticListener and corresponding Http listener. // We should ignore events for all of them except one if (!SubscriptionManager.IsActive(this)) { AspNetCoreEventSource.Instance.NotActiveListenerNoTracking( "Microsoft.AspNetCore.Hosting.BeginRequest", Activity.Current?.Id); return; } // 1.XX does not create Activity and SDK is responsible for creating Activity. var activity = new Activity(ActivityCreatedByHostingDiagnosticListener); IHeaderDictionary requestHeaders = httpContext.Request.Headers; // Update the static RoleName while we have access to the httpContext. RoleNameContainer.Instance?.Set(requestHeaders); string originalParentId = null; string legacyRootId = null; // W3C-TraceParent if (Activity.DefaultIdFormat == ActivityIdFormat.W3C && requestHeaders.TryGetValue(W3C.W3CConstants.TraceParentHeader, out StringValues traceParentValues) && traceParentValues != StringValues.Empty) { var parentTraceParent = StringUtilities.EnforceMaxLength(traceParentValues.First(), InjectionGuardConstants.TraceParentHeaderMaxLength); activity.SetParentId(parentTraceParent); originalParentId = parentTraceParent; ReadTraceState(requestHeaders, activity); } // Request-Id else if (requestHeaders.TryGetValue(RequestResponseHeaders.RequestIdHeader, out StringValues requestIdValues) && requestIdValues != StringValues.Empty) { originalParentId = StringUtilities.EnforceMaxLength(requestIdValues.First(), InjectionGuardConstants.RequestHeaderMaxLength); if (Activity.DefaultIdFormat == ActivityIdFormat.W3C) { if (TryGetW3CCompatibleTraceId(originalParentId, out var traceId)) { activity.SetParentId(ActivityTraceId.CreateFromString(traceId), default(ActivitySpanId), ActivityTraceFlags.None); } else { // store rootIdFromOriginalParentId in custom Property legacyRootId = ExtractOperationIdFromRequestId(originalParentId); } } else { activity.SetParentId(originalParentId); } } // no headers else { // No need of doing anything. When Activity starts, it'll generate IDs in W3C or Hierarchical format as configured, } activity.Start(); ReadCorrelationContext(requestHeaders, activity); var requestTelemetry = this.InitializeRequestTelemetry(httpContext, activity, timestamp, legacyRootId); requestTelemetry.Context.Operation.ParentId = GetParentId(activity, originalParentId); this.AddAppIdToResponseIfRequired(httpContext, requestTelemetry); } }
/// <summary> /// Redirects the client to the specified file. /// </summary> public void ReturnFile(Stream stream, string fileName, string mimeType, IHeaderDictionary additionalHeaders = null) { var returnedFileStorage = Configuration.ServiceLocator.GetService<IReturnedFileStorage>(); var metadata = new ReturnedFileMetadata() { FileName = fileName, MimeType = mimeType, AdditionalHeaders = additionalHeaders?.ToDictionary(k => k.Key, k => k.Value) }; var generatedFileId = returnedFileStorage.StoreFile(stream, metadata).Result; RedirectToUrl("~/dotvvmReturnedFile?id=" + generatedFileId); }
public static void AppendHeaderUnmodified(IHeaderDictionary headers, string key, StringValues values) { if (headers == null) { throw new ArgumentNullException(nameof(headers)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (values.Count == 0) { return; } var existing = GetHeaderUnmodified(headers, key); SetHeaderUnmodified(headers, key, StringValues.Concat(existing, values)); }
/// <summary> /// Validates that filterUid has changed i.e. updated/deleted but not inserted /// </summary> public async Task <BaseMasterDataResult> NotifyFilterChange(Guid filterUid, Guid projectUid, IHeaderDictionary customHeaders = null) { log.LogDebug($"{nameof(NotifyFilterChange)} filterUid: {filterUid}, projectUid: {projectUid}"); var queryParams = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("filterUid", filterUid.ToString()), new KeyValuePair <string, string>("projectUid", projectUid.ToString()) }; var response = await GetMasterDataItemServiceDiscoveryNoCache <BaseMasterDataResult>("/notification/filterchange", customHeaders, queryParams); log.LogDebug($"{nameof(NotifyFilterChange)} response: {(response == null ? null : JsonConvert.SerializeObject(response).Truncate(LogMaxChar))}"); return(response); }
/// <summary> /// Add to IfNoneMatch values. /// </summary> /// <returns>The IfNoneMatch values.</returns> public static void AddIfNoneMatch(this IHeaderDictionary headers, EntityTagHeaderValue value) { StringValues newValue = StringValues.Concat(headers["If-None-Match"], new StringValues(value.ToString())); headers["If-None-Match"] = newValue; }
static void AppendHeaderValue(ClientWebSocketOptions options, IHeaderDictionary headers, string key, string value) { var newValue = new StringValues(headers[key].Append(value).ToArray()); options.SetRequestHeader(key, newValue); }
public async Task <BaseMasterDataResult> UpdateFiles(Guid projectUid, IEnumerable <Guid> fileUids, IHeaderDictionary customHeaders = null) { var fileUidsList = fileUids.ToList(); log.LogDebug($"{nameof(UpdateFiles)} projectUid: {projectUid} fileUids: {string.Join<Guid>(",", fileUidsList)}"); //var queryParams = $"?projectUid={projectUid}&fileUids={string.Join<Guid>("&fileUids=", fileUids)}"; var queryParams = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("projectUid", projectUid.ToString()) }; foreach (var fileUid in fileUidsList) { queryParams.Add(new KeyValuePair <string, string>("fileUids", fileUid.ToString())); } return(await NotifyFile <BaseMasterDataResult>("/notification/updatefiles", queryParams, customHeaders)); }
public RequestHeadersWrapper(IHeaderDictionary headers) { _innerHeaders = headers; }
public async Task <BaseMasterDataResult> DeleteFile(Guid projectUid, ImportedFileType fileType, Guid fileUid, string fileDescriptor, long fileId, long?legacyFileId, IHeaderDictionary customHeaders = null) { log.LogDebug($"{nameof(DeleteFile)} projectUid: {projectUid} fileUid: {fileUid} fileDescriptor: {fileDescriptor} fileId: {fileId} legacyFileId: {legacyFileId}"); var queryParams = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("projectUid", projectUid.ToString()), new KeyValuePair <string, string>("fileType", fileType.ToString()), new KeyValuePair <string, string>("fileUid", fileUid.ToString()), new KeyValuePair <string, string>("fileDescriptor", fileDescriptor), new KeyValuePair <string, string>("fileId", fileId.ToString()) }; return(await NotifyFile <BaseMasterDataResult>("/notification/deletefile", queryParams, customHeaders)); }
public async Task <AddFileResult> AddFile(Guid projectUid, ImportedFileType fileType, Guid fileUid, string fileDescriptor, long fileId, DxfUnitsType dxfUnitsType, IHeaderDictionary customHeaders = null) { log.LogDebug($"{nameof(AddFile)} projectUid: {projectUid} fileUid: {fileUid} fileDescriptor: {fileDescriptor} fileId: {fileId} dxfUnitsType: {dxfUnitsType}"); var queryParams = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("projectUid", projectUid.ToString()), new KeyValuePair <string, string>("fileType", fileType.ToString()), new KeyValuePair <string, string>("fileUid", fileUid.ToString()), new KeyValuePair <string, string>("fileDescriptor", fileDescriptor), new KeyValuePair <string, string>("fileId", fileId.ToString()), new KeyValuePair <string, string>("dxfUnitsType", dxfUnitsType.ToString()) }; return(await NotifyFile <AddFileResult>("/notification/addfile", queryParams, customHeaders)); }
/// <summary> /// Notifies TRex/Raptor that a file has been added to or deleted from a project /// </summary> private async Task <T> NotifyFile <T>(string route, IList <KeyValuePair <string, string> > queryParams, IHeaderDictionary customHeaders) where T : class, IMasterDataModel { T response = await GetMasterDataItemServiceDiscoveryNoCache <T>(route, customHeaders, queryParams); log.LogDebug($"{nameof(NotifyFile)} response: {(response == null ? null : JsonConvert.SerializeObject(response).Truncate(LogMaxChar))}"); return(response); }
public EtagHandlerFeature(IHeaderDictionary headers) { _headers = headers; }
// internal for testing internal static IEnumerable <ForwardedHeaderValue> GetCurrentForwardedHeaderValues(IHeaderDictionary headers) { bool hasForwarded = false; foreach (var value in headers.GetCommaSeparatedHeaderValues(Names.Forwarded)) { if (TryParseForwardedHeaderValue(value, out var forwardedValue)) { hasForwarded = true; yield return(forwardedValue); } } if (hasForwarded) { yield break; } foreach (var @for in headers.GetCommaSeparatedHeaderValues(Names.XForwardedFor)) { yield return(new ForwardedHeaderValue(@for: @for)); } }
public static void AppendHeaderJoined(IHeaderDictionary headers, string key, params string[] values) { if (headers == null) { throw new ArgumentNullException(nameof(headers)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (values == null || values.Length == 0) { return; } string existing = GetHeader(headers, key); if (existing == null) { SetHeaderJoined(headers, key, values); } else { headers[key] = existing + "," + string.Join(",", values.Select(value => QuoteIfNeeded(value))); } }
/// <summary> /// user token /// </summary> public async Task <AccountResponseModel> GetMyAccount(Guid userUid, Guid customerUid, IHeaderDictionary customHeaders = null) { var accountListResponseModel = await GetMyAccounts(userUid, customHeaders); if (accountListResponseModel == null || accountListResponseModel.Accounts.Count == 0) { return(null); } var accountResponseModel = accountListResponseModel.Accounts .Find(a => string.Equals(a.Id, customerUid.ToString(), StringComparison.InvariantCultureIgnoreCase)); log.LogDebug($"{nameof(GetMyAccount)}: accountResponseModel {JsonConvert.SerializeObject(accountResponseModel)}"); return(accountResponseModel); }
public async Task HeadersAndStreamsAreReusedAcrossRequests() { var testContext = new TestServiceContext(LoggerFactory); var streamCount = 0; var requestHeadersCount = 0; var responseHeadersCount = 0; var loopCount = 20; Stream lastStream = null; IHeaderDictionary lastRequestHeaders = null; IHeaderDictionary lastResponseHeaders = null; using (var server = new TestServer(async context => { if (context.Request.Body != lastStream) { lastStream = context.Request.Body; streamCount++; } if (context.Request.Headers != lastRequestHeaders) { lastRequestHeaders = context.Request.Headers; requestHeadersCount++; } if (context.Response.Headers != lastResponseHeaders) { lastResponseHeaders = context.Response.Headers; responseHeadersCount++; } var ms = new MemoryStream(); await context.Request.Body.CopyToAsync(ms); var request = ms.ToArray(); context.Response.ContentLength = request.Length; await context.Response.Body.WriteAsync(request, 0, request.Length); }, testContext)) { using (var connection = server.CreateConnection()) { var requestData = Enumerable.Repeat("GET / HTTP/1.1\r\nHost:\r\n", loopCount) .Concat(new[] { "GET / HTTP/1.1\r\nHost:\r\nContent-Length: 7\r\nConnection: close\r\n\r\nGoodbye" }); var response = string.Join("\r\n", new string[] { "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Content-Length: 0", "" }); var lastResponse = string.Join("\r\n", new string[] { "HTTP/1.1 200 OK", "Connection: close", $"Date: {testContext.DateHeaderValue}", "Content-Length: 7", "", "Goodbye" }); var responseData = Enumerable.Repeat(response, loopCount) .Concat(new[] { lastResponse }); await connection.Send(requestData.ToArray()); await connection.ReceiveEnd(responseData.ToArray()); } Assert.Equal(1, streamCount); Assert.Equal(1, requestHeadersCount); Assert.Equal(1, responseHeadersCount); } }
/// <summary> /// application token and user token /// used by UI to determine functionality allowed by user token /// used by TFA using an application token /// </summary> public async Task <DeviceLicenseResponseModel> GetDeviceLicenses(Guid customerUid, IHeaderDictionary customHeaders = null) { log.LogDebug($"{nameof(GetDeviceLicenses)}: customerUid {customerUid}"); var accountTrn = TRNHelper.MakeTRN(customerUid, TRNHelper.TRN_ACCOUNT); var deviceLicenseResponseModel = await GetData <DeviceLicenseResponseModel>($"/accounts/{accountTrn}/devicelicense", customerUid, null, null, customHeaders); log.LogDebug($"{nameof(GetDeviceLicenses)}: deviceLicenseResponseModel {JsonConvert.SerializeObject(deviceLicenseResponseModel)}"); return(deviceLicenseResponseModel); }
public RequestBuilder WithHeaders(IHeaderDictionary headers) { _headers = headers; return(this); }
public async Task Finish() { if (_minificationEnabled) { byte[] cachedBytes = _cachedStream.ToArray(); int cachedByteCount = cachedBytes.Length; bool isMinified = false; if (cachedByteCount > 0 && _options.IsAllowableResponseSize(cachedByteCount)) { Encoding encoding = _encoding ?? Encoding.GetEncoding(0); string content = encoding.GetString(cachedBytes); IMarkupMinifier minifier = _currentMinificationManager.CreateMinifier(); MarkupMinificationResult minificationResult = minifier.Minify(content, _currentUrl, _encoding, _currentMinificationManager.GenerateStatistics); if (minificationResult.Errors.Count == 0) { IHeaderDictionary responseHeaders = _context.Response.Headers; Action <string, string> appendHttpHeader = (key, value) => { responseHeaders.Append(key, new StringValues(value)); }; if (_options.IsPoweredByHttpHeadersEnabled()) { _currentMinificationManager.AppendPoweredByHttpHeader(appendHttpHeader); } responseHeaders.Remove(HeaderNames.ContentMD5); string processedContent = minificationResult.MinifiedContent; byte[] processedBytes = encoding.GetBytes(processedContent); int processedByteCount = processedBytes.Length; if (_compressionEnabled) { _currentCompressor.AppendHttpHeaders(appendHttpHeader); responseHeaders.Remove(HeaderNames.ContentLength); await _compressionStream.WriteAsync(processedBytes, 0, processedByteCount); } else { responseHeaders[HeaderNames.ContentLength] = processedByteCount.ToString(); await _originalStream.WriteAsync(processedBytes, 0, processedByteCount); } isMinified = true; } if (!isMinified) { Stream outputStream = _compressionStream ?? _originalStream; _cachedStream.Seek(0, SeekOrigin.Begin); await _cachedStream.CopyToAsync(outputStream); } } } }
/// <summary> /// Sends data stream to client. /// </summary> /// <param name="stream">Data to be sent.</param> /// <param name="fileName">Name of file.</param> /// <param name="mimeType">MIME type.</param> /// <param name="additionalHeaders">Additional headers.</param> public void ReturnFile(Stream stream, string fileName, string mimeType, IHeaderDictionary additionalHeaders) { var bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); ReturnFile(bytes, fileName, mimeType, additionalHeaders); }
public ResponseFeature(ResponseMessage responseMessage) { ResponseMessage = responseMessage; _headers = new HeaderCollectionWrapper(responseMessage.Headers); }
/// <summary> /// Parses http request headers into a Basic auth credential string value /// </summary> /// <param name="headers">Headers from http request</param> /// <param name="basicAuthValue">The parsed value from the Basic auth header if it exists, Null if it cant be parsed</param> /// <returns>True if has a valid Basic auth header, otherwise False</returns> public bool TryParseBasicAuthHeader(IHeaderDictionary headers, out string basicAuthValue) { StringValues authHeaderValues; bool hasAuthHeader = headers.TryGetValue(BasicAuthConstants.AuthHeaderName, out authHeaderValues) && authHeaderValues.Any(); if (!hasAuthHeader) { this.logger?.LogDebug("Request does not contain a Basic auth header."); basicAuthValue = null; return false; } basicAuthValue = authHeaderValues.First(); bool headerIsBasicAuth = basicAuthValue.StartsWith("Basic "); if (!headerIsBasicAuth) { this.logger?.LogDebug("Request has an authentication header but is is not the Basic auth scheme."); basicAuthValue = null; return false; } return true; }
static bool RequestParameterVerification(IHeaderDictionary headers, IDictionary <string, string> args, out ResultCode resultCode) { string restMethod = headers[HeaderKeyConstant.REST_METHOD]; string restAppKey = headers[HeaderKeyConstant.REST_APP_KEY]; string restSignMethod = headers[HeaderKeyConstant.REST_SIGN_METHOD]; string restSign = headers[HeaderKeyConstant.REST_SIGN]; string restTimestamp = headers[HeaderKeyConstant.REST_TIMESTAMP]; #region 验证必填 if (string.IsNullOrEmpty(restMethod) || string.IsNullOrEmpty(restAppKey) || string.IsNullOrEmpty(restSignMethod) || string.IsNullOrEmpty(restSign) || string.IsNullOrEmpty(restTimestamp) ) { resultCode = ResultCode.RequestParameterIncomplete; return(false); } #endregion #region 验证APPKey if (!Global.App.ContainsKey(restAppKey)) { resultCode = ResultCode.AppKeyNotFound; return(false); } string appSecret = Global.App[restAppKey]; #endregion #region 验证时间戳 DateTime timestamp = DateTime.MinValue; if (!DateTime.TryParseExact(restTimestamp, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out timestamp)) { resultCode = ResultCode.TimeFormat; return(false); } DateTime maxTime = DateTime.Now; DateTime minTime = maxTime.AddMinutes(-1); if (timestamp < minTime || timestamp > maxTime) { resultCode = ResultCode.Timestamp; return(false); } #endregion #region 验证API方法 if (!Global.Service.ContainsKey(restMethod)) { resultCode = ResultCode.MethodNotFound; return(false); } #endregion #region 验证签名 if (CommonConstant.SIGN_METHOD_MD5.Equals(restSignMethod) || CommonConstant.SIGN_METHOD_HMAC.Equals(restSignMethod)) { string signNew = Common.BuildSign(args, appSecret, restSignMethod); if (!signNew.Equals(restSign)) { resultCode = ResultCode.SignError; return(false); } } else { resultCode = ResultCode.SignError; return(false); } #endregion resultCode = ResultCode.Success; return(true); }
static IContentFormatter SelectAcceptEncodingFormatter(IHeaderDictionary requestHeader, ICollection<IContentFormatter> selectedFormatters) { if (selectedFormatters.Count == 1) return selectedFormatters.First(); StringValues rawAcceptEncoding; if (!requestHeader.TryGetValue("Accept-Encoding", out rawAcceptEncoding)) { return selectedFormatters.First(); } var acceptEncodings = GetDescendingQualityHeaderValues(rawAcceptEncoding); var formatter = acceptEncodings .Select(kvp => selectedFormatters.FirstOrDefault(x => kvp.Item3.Equals(x.ContentEncoding, StringComparison.OrdinalIgnoreCase))) .FirstOrDefault(x => x != null); if (formatter == null) return selectedFormatters.First(); return formatter; }
public static Dictionary <string, object> Convert2Dictionary(this IHeaderDictionary headerDictionary) { return(Convert(headerDictionary)); }
public IEnumerable <Claim> GetExtendedClaims(ClaimsPrincipal currentPrincipal, IHeaderDictionary requestHeaders) { // If this is being called by a service principal (which means there won't be a // tenant specified in the JWT), we should check to see if a tenant was passed // in the header. If so, let's use that one because we implicitly trust // microservices to be making requests on behalf of an authorized tenant user. if (!currentPrincipal.IsServicePrincipal()) { yield break; } if (requestHeaders.ContainsKey(HeaderKeys.Tenant) && Guid.TryParse(requestHeaders[HeaderKeys.Tenant], out var tenantId)) { yield return(new Claim(Authentication.Jwt.ClaimTypes.Tenant, tenantId.ToString())); } }
public static void SetHeaderUnmodified(IHeaderDictionary headers, string key, StringValues? values) { if (headers == null) { throw new ArgumentNullException(nameof(headers)); } if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException(nameof(key)); } if (!values.HasValue || StringValues.IsNullOrEmpty(values.Value)) { headers.Remove(key); } else { headers[key] = values.Value; } }
public void ReturnFile(byte[] bytes, string fileName, string mimeType, IHeaderDictionary additionalHeaders) { throw new DotvvmInterruptRequestExecutionException(InterruptReason.ReturnFile, fileName); }
public ODataMessageWrapper(Stream stream, IHeaderDictionary headers) : this(stream: stream, headers: headers, contentIdMapping: null) { }
private bool ValidateAcceptHeader(IHeaderDictionary headers) { var acceptsHeaders = headers["Accept"].FirstOrDefault(); if (string.IsNullOrEmpty(acceptsHeaders)) { return true; } return acceptsHeaders .Split(',') .Select(x => x.Trim()) .Any(x => x == "*/*" || x == configuration.DefaultJsonApiMediaType.MediaType); }
/// <summary> /// Quotes any values containing commas, and then comma joins all of the values. /// </summary> /// <param name="headers">The <see cref="IHeaderDictionary"/> to use.</param> /// <param name="key">The header name.</param> /// <param name="values">The header values.</param> public static void SetCommaSeparatedValues(this IHeaderDictionary headers, string key, params string[] values) { ParsingHelpers.SetHeaderJoined(headers, key, values); }
public static StringValues GetHeader(IHeaderDictionary headers, string key) { StringValues value; return headers.TryGetValue(key, out value) ? value : StringValues.Empty; }
public ObjectWithHeadersResult(object value, IHeaderDictionary headers) : base(value) { Headers = headers ?? new HeaderDictionary(); }
public static StringValues GetHeaderSplit(IHeaderDictionary headers, string key) { var values = GetHeaderUnmodified(headers, key); return new StringValues(GetHeaderSplitImplementation(values).ToArray()); }
public Headers(IHeaderDictionary headers) { this.headers = headers; }
/// <summary> /// Add new values. Each item remains a separate array entry. /// </summary> /// <param name="headers">The <see cref="IHeaderDictionary"/> to use.</param> /// <param name="key">The header name.</param> /// <param name="value">The header value.</param> public static void Append(this IHeaderDictionary headers, string key, StringValues value) { ParsingHelpers.AppendHeaderUnmodified(headers, key, value); }
/// <summary> /// Notifies TRex/Raptor that a file has been CRUD to a project via CGen /// </summary> /// <summary> /// Notifies TRex/Raptor that a file has been CRUD to a project via CGen /// </summary> public async Task <BaseMasterDataResult> NotifyImportedFileChange(Guid projectUid, Guid fileUid, IHeaderDictionary customHeaders = null) { log.LogDebug($"{nameof(NotifyImportedFileChange)} projectUid: {projectUid} fileUid: {fileUid}"); var queryParams = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("projectUid", projectUid.ToString()), new KeyValuePair <string, string>("fileUid", fileUid.ToString()) }; return(await NotifyFile <BaseMasterDataResult>("/notification/importedfilechange", queryParams, customHeaders)); }
/// <summary> /// Get the associated values from the collection separated into individual values. /// Quoted values will not be split, and the quotes will be removed. /// </summary> /// <param name="headers">The <see cref="IHeaderDictionary"/> to use.</param> /// <param name="key">The header name.</param> /// <returns>the associated values from the collection separated into individual values, or StringValues.Empty if the key is not present.</returns> public static string[] GetCommaSeparatedValues(this IHeaderDictionary headers, string key) { return(ParsingHelpers.GetHeaderSplit(headers, key)); }
private void Initialize() { if (_wrapperInitializedFlag.Set()) { HttpRequest request = _context.Request; HttpResponse response = _context.Response; if (response.StatusCode == 200) { string httpMethod = request.Method; string contentType = response.ContentType; string mediaType = null; Encoding encoding = null; if (contentType != null) { MediaTypeHeaderValue mediaTypeHeader; if (MediaTypeHeaderValue.TryParse(contentType, out mediaTypeHeader)) { mediaType = mediaTypeHeader.MediaType #if ASPNETCORE2 || ASPNETCORE3 .Value #endif .ToLowerInvariant() ; encoding = mediaTypeHeader.Encoding; } } string currentUrl = request.Path.Value; QueryString queryString = request.QueryString; if (queryString.HasValue) { currentUrl += queryString.Value; } IHeaderDictionary responseHeaders = response.Headers; bool isEncodedContent = responseHeaders.IsEncodedContent(); int minificationManagerCount = _minificationManagers.Count; if (minificationManagerCount > 0) { for (int managerIndex = 0; managerIndex < minificationManagerCount; managerIndex++) { IMarkupMinificationManager minificationManager = _minificationManagers[managerIndex]; if (minificationManager.IsSupportedHttpMethod(httpMethod) && mediaType != null && minificationManager.IsSupportedMediaType(mediaType) && minificationManager.IsProcessablePage(currentUrl)) { if (isEncodedContent) { throw new InvalidOperationException( string.Format( AspNetCommonStrings.MarkupMinificationIsNotApplicableToEncodedContent, responseHeaders[HeaderNames.ContentEncoding] ) ); } _currentMinificationManager = minificationManager; _cachedStream = new MemoryStream(); _minificationEnabled = true; break; } } } if (_compressionManager != null && !isEncodedContent && _compressionManager.IsSupportedHttpMethod(httpMethod) && _compressionManager.IsSupportedMediaType(mediaType) && _compressionManager.IsProcessablePage(currentUrl)) { string acceptEncoding = request.Headers[HeaderNames.AcceptEncoding]; ICompressor compressor = InitializeCurrentCompressor(acceptEncoding); if (compressor != null) { _compressionStream = compressor.Compress(_originalStream); _compressionEnabled = true; } } _currentUrl = currentUrl; _encoding = encoding; } } }
/// <inheritdoc /> public IAndHttpResponseTestBuilder ContainingHeaders(IHeaderDictionary headers) { this.ValidateHeadersCount(headers.Count); headers.ForEach(h => this.ContainingHeader(h.Key, h.Value)); return(this); }
private async Task <HttpResponseMessage> ProcessRequestAsync(string method, string all, object content, IHeaderDictionary headers = null) { var graphClient = _graphSdkHelper.GetAuthenticatedClient(); var request = new BaseRequest(GetURL(all, graphClient), graphClient, null) { Method = method, ContentType = HttpContext.Request.ContentType, }; var neededHeaders = Request.Headers.Where(h => h.Key.ToLower() == "if-match").ToList(); if (neededHeaders.Count() > 0) { foreach (var header in neededHeaders) { request.Headers.Add(new HeaderOption(header.Key, string.Join(",", header.Value))); } } var contentType = "application/json"; try { using (var response = await request.SendRequestAsync(content, CancellationToken.None, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false)) { response.Content.Headers.TryGetValues("content-type", out var contentTypes); contentType = contentTypes?.FirstOrDefault() ?? contentType; var byteArrayContent = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); return(ReturnHttpResponseMessage(HttpStatusCode.OK, contentType, new ByteArrayContent(byteArrayContent))); } } catch (ServiceException ex) { return(ReturnHttpResponseMessage(ex.StatusCode, contentType, new StringContent(ex.Error.ToString()))); } }
private static HttpResponse CreateResponse(IHeaderDictionary headers) { var context = new DefaultHttpContext(); context.Features.Get<IHttpResponseFeature>().Headers = headers; return context.Response; }
private static void SetRequestHeaders(HttpWebRequest request, IHeaderDictionary requestHeaders) { // copy headers to avoid messing with original request headers Dictionary<string, string> headers = new Dictionary<string, string>(); foreach (var pair in requestHeaders) { headers.Add(pair.Key, string.Join(", ", pair.Value)); } string valueAccept; if (headers.TryGetValue("Accept", out valueAccept)) { request.Accept = valueAccept; headers.Remove("Accept"); } string valueConnection; if (headers.TryGetValue("Connection", out valueConnection)) { if (valueConnection.EqualsIgnoreCase("keep-alive")) { request.KeepAlive = true; } else if (valueConnection.EqualsIgnoreCase("close")) { request.KeepAlive = false; } else { request.Connection = valueConnection; } headers.Remove("Connection"); } string valueContentLength; if (headers.TryGetValue("Content-Length", out valueContentLength)) { request.ContentLength = valueContentLength.ToLongOrDefault(); headers.Remove("Content-Length"); } string valueContentType; if (headers.TryGetValue("Content-Type", out valueContentType)) { request.ContentType = valueContentType; headers.Remove("Content-Type"); } string valueExcept; if (headers.TryGetValue("Expect", out valueExcept)) { request.Expect = valueExcept; headers.Remove("Expect"); } string valueDate; if (headers.TryGetValue("Date", out valueDate)) { request.Date = valueDate.ToDateTimeOrDefault(); headers.Remove("Date"); } string valueHost; if (headers.TryGetValue("Host", out valueHost)) { request.Host = valueHost; headers.Remove("Host"); } string valueIfModifiedSince; if (headers.TryGetValue("If-Modified-Since", out valueIfModifiedSince)) { request.IfModifiedSince = valueIfModifiedSince.ToDateTimeOrDefault(); headers.Remove("If-Modified-Since"); } string valueRange; if (headers.TryGetValue("Range", out valueRange)) { // TODO: AddRange headers.Remove("Range"); } string valueReferer; if (headers.TryGetValue("Referer", out valueReferer)) { request.Referer = valueReferer; headers.Remove("Referer"); } string valueTransferEncoding; if (headers.TryGetValue("Transfer-Encoding", out valueTransferEncoding)) { request.SendChunked = true; request.TransferEncoding = valueTransferEncoding; headers.Remove("Transfer-Encoding"); } string valueUserAgent; if (headers.TryGetValue("User-Agent", out valueUserAgent)) { request.UserAgent = valueUserAgent; headers.Remove("User-Agent"); } foreach (var pair in headers) { request.Headers.Add(pair.Key, pair.Value); } }
public HttpHeaderProvider(IHeaderDictionary headers) { _headers = headers; }
/// <summary> /// Gets If-Modified-Since time header from headers collection. /// </summary> /// <param name="headers">The headers.</param> /// <returns></returns> public DateTime? GetIfModifiedSinceTime(IHeaderDictionary headers) { return OwinHttpRequestHelper.GetIfModifiedSinceTime(headers); }
/// <summary> /// Initializes a new instance of the <see cref="MockedHttpRequest"/> class. /// </summary> public MockedHttpRequest(HttpContext httpContext) { CommonValidator.CheckForNullReference(httpContext, nameof(HttpContext)); this.httpContext = httpContext; this.headerDictionary = new HeaderDictionary(); this.formFiles = new FormFileCollection(); this.cookieValues = new Dictionary<string, string>(); this.formValues = new Dictionary<string, StringValues>(); this.queryValues = new Dictionary<string, StringValues>(); }