internal static Task CreateODataBatchResponseAsync(this HttpRequest request, IEnumerable <ODataBatchResponseItem> responses, ODataMessageQuotas messageQuotas) { Contract.Assert(request != null); ODataVersion odataVersion = GetODataResponseVersion(request); IServiceProvider requestContainer = request.GetSubServiceProvider(); ODataMessageWriterSettings writerSettings = requestContainer.GetRequiredService <ODataMessageWriterSettings>(); writerSettings.Version = odataVersion; writerSettings.MessageQuotas = messageQuotas; HttpResponse response = request.HttpContext.Response; StringValues acceptHeader = request.Headers["Accept"]; string responseContentType = null; if (StringValues.IsNullOrEmpty(acceptHeader)) { // In absence of accept, if request was JSON then default response to be JSON. // Note that, if responseContentType is not set, then it will default to multipart/mixed // when constructing the BatchContent, so we don't need to handle that case here if (!String.IsNullOrEmpty(request.ContentType) && request.ContentType.IndexOf(BatchMediaTypeJson, StringComparison.OrdinalIgnoreCase) > -1) { responseContentType = BatchMediaTypeJson; } } else if (acceptHeader.Any(h => h.Equals(BatchMediaTypeMime, StringComparison.OrdinalIgnoreCase))) { responseContentType = String.Format(CultureInfo.InvariantCulture, "multipart/mixed;boundary=batchresponse_{0}", Guid.NewGuid()); } else if (acceptHeader.Any(h => h.IndexOf(BatchMediaTypeJson, StringComparison.OrdinalIgnoreCase) > -1)) { responseContentType = BatchMediaTypeJson; } response.StatusCode = StatusCodes.Status200OK; ODataBatchContent batchContent = new ODataBatchContent(responses, requestContainer, responseContentType); foreach (var header in batchContent.Headers) { // Copy headers from batch content, overwriting any existing headers. response.Headers[header.Key] = header.Value; } return(batchContent.SerializeToStreamAsync(response.Body)); }
public static GroupingValues <string, string> Parse(StringValues values) { HashSet <Grouping <string, string> > groups = new HashSet <Grouping <string, string> >(); HashSet <string> individuals = new HashSet <string>(); foreach (StringSegment value in values.SelectMany(x => Delimiter.Parenthetical.Split(x))) { // TODO: C# 8.0 will support normal FP-style tuple match. // see: https://github.com/dotnet/csharplang/issues/1395 switch (Grouping <TKey, TValue> .TryParse(value.Value)) { case ValueTuple <bool, Grouping <string, string> > t when t.Item1: { groups.Add(t.Item2); continue; } default: { individuals.Add(value.Value); continue; } } } StringValues items = individuals.Except(groups.SelectMany(x => x)).ToArray(); if (items.Any()) { groups.Add(Grouping <string, string> .CreateIndividuals(items)); } return(new GroupingValues <string, string>(groups)); }
private async Task <string> GetUserAuthorizationJwtAsync( HttpContext httpContext, IHttpClientFactory httpClientFactory, IMemoryCache memoryCache, StringValues authHeader, int cacheKey, string authorizationUrl) { using (HttpClient client = httpClientFactory.CreateClient(AuthorizationHttpClientName)) { if (authHeader.Any()) { client.DefaultRequestHeaders.Add(HeaderNames.Authorization, authHeader.ToString()); } if (_jwtAuthorizationOptions.ForwardedHeaders.Any()) { AddForwardedHeaders(client, httpContext.Request.Headers); } string jwtToken = await client.GetStringAndCheckResponseAsync(authorizationUrl, new UnauthorizedAccessException(Properties.Resources.AuthorizationServiceForbiddenRequest)); SetTokenToCache(memoryCache, cacheKey, jwtToken, httpContext.Request); return(jwtToken); } }
public async Task Invoke(HttpContext context) { var remoteIpAddress = context.Connection.RemoteIpAddress; if (context.Request.Path.StartsWithSegments("/api")) { var req = context.Request; StringValues autHeader = req.Headers["Authorization"]; if (autHeader.Any())// && authenticationScheme.Equals(req.Scheme, StringComparison.OrdinalIgnoreCase)) { var headerparams = autHeader.FirstOrDefault().ToString().Split(' '); var scheme = headerparams[0]; if (string.CompareOrdinal(scheme, authenticationScheme) == 0) { var rawAuthzHeader = headerparams[1]; var autherizationHeaderArray = GetAutherizationHeaderValues(rawAuthzHeader); if (autherizationHeaderArray != null) { var APPId = autherizationHeaderArray[0]; var incomingBase64Signature = autherizationHeaderArray[1]; var nonce = autherizationHeaderArray[2]; var requestTimeStamp = autherizationHeaderArray[3]; byte[] hash = await ComputeHash(req); var requestContentBase64String = ""; if (hash != null) { requestContentBase64String = Convert.ToBase64String(hash); } Console.WriteLine(); var isValid = isValidRequest(req, APPId, incomingBase64Signature, nonce, requestTimeStamp); if (isValid.Result) { await _next.Invoke(context); return; } else { context.Response.StatusCode = 405; //Method Not Allowed await context.Response.WriteAsync("Method Not Allowed"); return; } } } context.Response.StatusCode = 405; //Method Not Allowed await context.Response.WriteAsync("Method Not Allowed"); return; } } }
private static StringValues SplitOnDelimiters(StringValues values, char[] delimiters) { if (values.Any(v => delimiters.Any(v.Contains))) { return(new StringValues(values .SelectMany(x => x.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)) .ToArray())); } return(values); }
public static void Forward(HttpRequest request, IForwardingClient client, string headerName, string headerForwardedName, string prependedText = "") { StringValues authToken = StringValues.Empty; request.Headers.TryGetValue(headerName, out authToken); if (authToken.Any()) { client.ForwardHeader(headerForwardedName, $"{prependedText}{authToken.First()}").Wait(); } }
public async Task Invoke(HttpContext httpContext) { try { var remoteIpAddress = httpContext.Connection.RemoteIpAddress; if (httpContext.Request.Path.StartsWithSegments("/api")) { var req = httpContext.Request; StringValues autHeader = req.Headers["Authorization"]; if (autHeader.Any())// && authenticationScheme.Equals(req.Scheme, StringComparison.OrdinalIgnoreCase)) { var headerparams = autHeader.FirstOrDefault().ToString().Split(' '); var scheme = headerparams[0]; var rawAuthzHeader = headerparams[1]; var autherizationHeaderArray = GetAutherizationHeaderValues(rawAuthzHeader); if (autherizationHeaderArray != null) { var APPId = autherizationHeaderArray[0]; var incomingBase64Signature = autherizationHeaderArray[1]; var nonce = autherizationHeaderArray[2]; var requestTimeStamp = autherizationHeaderArray[3]; //var isValid = isValidRequest(req, APPId, incomingBase64Signature, nonce, requestTimeStamp); //if (isValid.Result) //{ //var currentPrincipal = new GenericPrincipal(new GenericIdentity(APPId), null); //context.Principal = currentPrincipal; // } // else //{ //context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request); // } } if (httpContext.Request.Method != "POST") { httpContext.Response.StatusCode = 405; //Method Not Allowed await httpContext.Response.WriteAsync("Method Not Allowed"); return; } } } } catch (Exception ex) { } }
public bool CanTransform(HttpRequestRecord record, StringValues contentTypeHeaderValues) { // NOTE: Currently, this transformer can handle only Unary request. var methodHandler = _serviceDefinition.MethodHandlers.FirstOrDefault(x => string.Concat("/" + x.ServiceName, "/", x.MethodName) == record.Path); if (methodHandler == null || methodHandler.MethodType != MethodType.Unary) { return(false); } return(contentTypeHeaderValues.Any(x => x == "application/grpc")); }
internal static Task CreateODataBatchResponseAsync(this HttpRequest request, IEnumerable <ODataBatchResponseItem> responses, ODataMessageQuotas messageQuotas) { Contract.Assert(request != null); ODataVersion odataVersion = ODataInputFormatter.GetODataResponseVersion(request); IServiceProvider requestContainer = request.GetRequestContainer(); ODataMessageWriterSettings writerSettings = requestContainer.GetRequiredService <ODataMessageWriterSettings>(); writerSettings.Version = odataVersion; writerSettings.MessageQuotas = messageQuotas; HttpResponse response = request.HttpContext.Response; StringValues acceptHeader = request.Headers["Accept"]; string contentType = null; if (StringValues.IsNullOrEmpty(acceptHeader) || acceptHeader.Any(h => h.Equals(ODataBatchHttpRequestExtensions.BatchMediaTypeMime, StringComparison.OrdinalIgnoreCase))) { contentType = String.Format(CultureInfo.InvariantCulture, "multipart/mixed;boundary=batchresponse_{0}", Guid.NewGuid()); } else if (acceptHeader.Any(h => h.Equals(ODataBatchHttpRequestExtensions.BatchMediaTypeJson, StringComparison.OrdinalIgnoreCase))) { contentType = ODataBatchHttpRequestExtensions.BatchMediaTypeJson; } response.StatusCode = (int)HttpStatusCode.OK; ODataBatchContent batchContent = new ODataBatchContent(responses, requestContainer, contentType); foreach (var header in batchContent.Headers) { // Copy headers from batch content, overwriting any existing headers. response.Headers[header.Key] = header.Value; } return(batchContent.SerializeToStreamAsync(response.Body)); }
internal static QueryRequest ReadRequest(HttpContext context) { IQueryCollection requestQuery = context.Request.Query; StringValues variables = requestQuery[_variablesIdentifier]; return(new QueryRequest { Query = requestQuery[_queryIdentifier].ToString(), NamedQuery = requestQuery[_namedQueryIdentifier].ToString(), OperationName = requestQuery[_operationNameIdentifier].ToString(), Variables = variables.Any() ? JObject.Parse(variables) : null }); }
public Uri ResolveRouteUrl(IEnumerable <Tuple <string, string> > unsupportedSearchParams = null, string continuationToken = null) { string routeName = _fhirRequestContextAccessor.FhirRequestContext.RouteName; Debug.Assert(!string.IsNullOrWhiteSpace(routeName), "The routeName should not be null or empty."); var routeValues = new RouteValueDictionary(); // We could have multiple query parameters with the same name. In this case, we should only remove // the query parameter that was not used or not supported. ILookup <string, string> searchParamsToRemove = (unsupportedSearchParams ?? Enumerable.Empty <Tuple <string, string> >()) .ToLookup(sp => sp.Item1, sp => sp.Item2, StringComparer.OrdinalIgnoreCase); // Add all query parameters except those that were not used. if (Request.Query != null) { foreach (KeyValuePair <string, StringValues> searchParam in Request.Query) { // Remove the parameter if: // 1. It is the continuation token (if there is a new continuation token, then it will be added again). // 2. The parameter is not supported. if (!string.Equals(searchParam.Key, KnownQueryParameterNames.ContinuationToken, StringComparison.OrdinalIgnoreCase)) { IEnumerable <string> removedValues = searchParamsToRemove[searchParam.Key]; StringValues usedValues = removedValues.Any() ? new StringValues(searchParam.Value.Except(removedValues).ToArray()) : searchParam.Value; if (usedValues.Any()) { routeValues.Add(searchParam.Key, usedValues); } } } } if (continuationToken != null) { routeValues[KnownQueryParameterNames.ContinuationToken] = continuationToken; } string uriString = UrlHelper.RouteUrl( routeName, routeValues, Request.Scheme, Request.Host.Value); return(new Uri(uriString)); }
public static CompressionType?GetType(StringValues contentEncoding) { if (!contentEncoding.Any()) { return(CompressionType.Unknown); } StringWithQualityHeaderValue.TryParseList(contentEncoding, out var encodingsList); if (encodingsList == null || !encodingsList.Any()) { return(CompressionType.Unknown); } return(GetType(encodingsList)); }
public override void OnActionExecuting(ActionExecutingContext context) { if (!_authOptions.AuthHeaderCheckEnabled) { return; } StringValues values = new StringValues(); if (context.HttpContext.Request.Headers.TryGetValue("authorization_mobile", out values)) { if (!values.Any()) { context.Result = new UnauthorizedObjectResult("Missing or invalid token"); } else { var token = values.First(); string mobileTokenDecrypted; try { mobileTokenDecrypted = ConfigEncryptionHelper.UnprotectString(_mobileTokenEncrypted); } catch (Exception e) { _logger.LogError($"Configuration error. Cannot decrypt the mobileToken from configuration. MobileTokenEncrypted: {_mobileTokenEncrypted}. Message: {e.Message}"); throw; } if (!token.Equals(mobileTokenDecrypted) || string.IsNullOrEmpty(mobileTokenDecrypted)) { context.Result = new UnauthorizedObjectResult("Missing or invalid token"); } else { return; } } } else { context.Result = new UnauthorizedObjectResult("Missing or invalid token"); } }
private static async Task <bool> ValidateAcceptHeaderAsync(MediaTypeHeaderValue allowedMediaTypeValue, HttpContext httpContext, JsonSerializerSettings serializerSettings) { StringValues acceptHeaders = httpContext.Request.Headers["Accept"]; if (!acceptHeaders.Any()) { return(true); } bool seenCompatibleMediaType = false; foreach (string acceptHeader in acceptHeaders) { if (MediaTypeWithQualityHeaderValue.TryParse(acceptHeader, out MediaTypeWithQualityHeaderValue headerValue)) { headerValue.Quality = null; if (headerValue.MediaType == "*/*" || headerValue.MediaType == "application/*") { seenCompatibleMediaType = true; break; } if (allowedMediaTypeValue.Equals(headerValue)) { seenCompatibleMediaType = true; break; } } } if (!seenCompatibleMediaType) { await FlushResponseAsync(httpContext.Response, serializerSettings, new Error(HttpStatusCode.NotAcceptable) { Title = "The specified Accept header value does not contain any supported media types.", Detail = $"Please include '{allowedMediaTypeValue}' in the Accept header values." }); return(false); } return(true); }
public void OnAuthorization(AuthorizationFilterContext context) { if (!_authEnabled) { return; } StringValues apiKey = context.HttpContext.Request.Headers["X-API-KEY"]; if (apiKey.Any()) { if (apiKey[0] != _secureApiKey) { context.Result = new UnauthorizedResult(); } } else { context.Result = new UnauthorizedResult(); } }
private static IActionResult BuildBadReques(StringValues name, StringValues surname) { return((name.Any() || surname.Any()) ? new BadRequestObjectResult("Whats the heck is wrong with you ? Check name and surname params!") : null); }
public void OnException(ExceptionContext context) { StringValues contentTypes = new StringValues(); context.HttpContext.Request.Headers.TryGetValue("Content-Type", out contentTypes); object info = null, data = null; // FOR API if (!contentTypes.Any(o => o == "application/x-www-form-urlencoded")) { HttpStatusCode status = HttpStatusCode.InternalServerError; string message = context.Exception.Message; // FOR API if (context.Exception is DomainNullException || context.Exception.InnerException is DomainNullException) { DomainNullException ex; if (context.Exception is DomainNullException) { ex = context.Exception as DomainNullException; } else { ex = context.Exception.InnerException as DomainNullException; } context.ModelState.AddModelError(ex.ParamName, ex.Message); info = context.ModelState.Select(o => new { propertyName = o.Key, errors = o.Value.Errors.Select(e => e.ErrorMessage) }); message = ex.Message; status = HttpStatusCode.BadRequest; } else if (context.Exception is FluentValidation.ValidationException || context.Exception.InnerException is FluentValidation.ValidationException) { FluentValidation.ValidationException ex; if (context.Exception is FluentValidation.ValidationException) { ex = context.Exception as FluentValidation.ValidationException; } else { ex = context.Exception.InnerException as FluentValidation.ValidationException; } foreach (var failures in ex.Errors) { context.ModelState.AddModelError(failures.PropertyName, failures.ErrorMessage); } info = context.ModelState.Select(o => new { propertyName = o.Key, errors = o.Value.Errors.Select(e => e.ErrorMessage) }); message = ex.Message; status = HttpStatusCode.BadRequest; } context.ExceptionHandled = true; HttpResponse response = context.HttpContext.Response; response.StatusCode = (int)status; response.ContentType = "application/json"; response.WriteAsync(JsonConvert.SerializeObject(new { apiVersion = _workContext.ApiVersion, success = false, data, info, message, trace = context.Exception.StackTrace })); } // FOR MVC }
public static string GetValueOrEmpty(this StringValues val) => val.Any() ? val.ToString() : null;
public async Task <ActionResult> SearchMessageBoxInstances( [FromQuery(Name = "instanceOwner.partyId")] int instanceOwnerPartyId, [FromQuery] string appId, [FromQuery] bool includeActive, [FromQuery] bool includeArchived, [FromQuery] bool includeDeleted, [FromQuery] string lastChanged, [FromQuery] string created, [FromQuery] string searchString, [FromQuery] string archiveReference, [FromQuery] string language) { string[] acceptedLanguages = { "en", "nb", "nn" }; string languageId = "nb"; if (language != null && acceptedLanguages.Contains(language.ToLower())) { languageId = language.ToLower(); } Dictionary <string, StringValues> queryParams = QueryHelpers.ParseQuery(Request.QueryString.Value); if (!string.IsNullOrEmpty(archiveReference)) { if ((includeActive == includeArchived) && (includeActive == includeDeleted)) { includeActive = false; includeDeleted = true; includeArchived = true; } else if (includeActive && !includeArchived && !includeDeleted) { return(Ok(new List <MessageBoxInstance>())); } else if (includeActive && (includeArchived || includeDeleted)) { includeActive = false; } } GetStatusFromQueryParams(includeActive, includeArchived, includeDeleted, queryParams); queryParams.Add("sortBy", "desc:lastChanged"); if (!string.IsNullOrEmpty(searchString)) { StringValues applicationIds = await MatchStringToAppTitle(searchString); if (!applicationIds.Any() || (!string.IsNullOrEmpty(appId) && !applicationIds.Contains(appId))) { return(Ok(new List <MessageBoxInstance>())); } else if (string.IsNullOrEmpty(appId)) { queryParams.Add("appId", applicationIds); } queryParams.Remove(nameof(searchString)); } InstanceQueryResponse queryResponse = await _instanceRepository.GetInstancesFromQuery(queryParams, string.Empty, 100); if (queryResponse?.Exception != null) { if (queryResponse.Exception.StartsWith("Unknown query parameter")) { return(BadRequest(queryResponse.Exception)); } return(StatusCode(500, queryResponse.Exception)); } if (queryResponse == null || queryResponse.Count <= 0) { return(Ok(new List <MessageBoxInstance>())); } List <Instance> allInstances = queryResponse.Instances; allInstances.RemoveAll(i => i.VisibleAfter > DateTime.UtcNow); allInstances.ForEach(i => { if (i.Status.IsArchived || i.Status.IsSoftDeleted) { i.DueBefore = null; } }); List <MessageBoxInstance> authorizedInstances = await _authorizationHelper.AuthorizeMesseageBoxInstances(HttpContext.User, allInstances); List <string> appIds = authorizedInstances.Select(i => InstanceHelper.GetAppId(i)).Distinct().ToList(); List <TextResource> texts = await _textRepository.Get(appIds, languageId); InstanceHelper.ReplaceTextKeys(authorizedInstances, texts, languageId); return(Ok(authorizedInstances)); }
public async Task <IActionResult> Register([FromBody] object model) { // if (!ModelState.IsValid) // { var remoteIpAddress = HttpContext.Connection.RemoteIpAddress; if (HttpContext.Request.Path.StartsWithSegments("/api")) { var req = HttpContext.Request; StringValues autHeader = req.Headers["Authorization"]; if (autHeader.Any())// && authenticationScheme.Equals(req.Scheme, StringComparison.OrdinalIgnoreCase)) { var headerparams = autHeader.FirstOrDefault().ToString().Split(' '); var scheme = headerparams[0]; var rawAuthzHeader = headerparams[1]; var autherizationHeaderArray = GetAutherizationHeaderValues(rawAuthzHeader); if (autherizationHeaderArray != null) { var APPId = autherizationHeaderArray[0]; var incomingBase64Signature = autherizationHeaderArray[1]; var nonce = autherizationHeaderArray[2]; var requestTimeStamp = autherizationHeaderArray[3]; System.Console.WriteLine(); byte[] hash = await ComputeHash(req); var requestContentBase64String = ""; if (hash != null) { requestContentBase64String = Convert.ToBase64String(hash); } Console.WriteLine(); //var isValid = isValidRequest(req, APPId, incomingBase64Signature, nonce, requestTimeStamp); //if (isValid.Result) //{ //var currentPrincipal = new GenericPrincipal(new GenericIdentity(APPId), null); //context.Principal = currentPrincipal; // } // else //{ //context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request); // } } } } /* string errorMsg = null; * * foreach (var test in ModelState.Values) * { * foreach (var msg in test.Errors) * { * errorMsg = msg.ErrorMessage; * } * } * return BadRequest(errorMsg); * } * * var account = await _accountRepository.GetSingle(acc => acc.Name == model.AccountName); * var role = ""; * if (account == null) * { * account = new Account * { * Name = model.AccountName * }; * role = "Admin"; * } * else * { * role = "User"; * } * * * var user = new ApplicationUser * { * UserName = model.Email, * Email = model.Email, * FirstName = model.FirstName, * LastName = model.LastName, * Account = account, * AccountID = account.AccountID * }; * * var result = await _userManager.CreateAsync(user, model.Password); * * if (result.Succeeded) * { * var userAccount = await _userManager.FindByEmailAsync(model.Email); * // This code can be deleted when the user must activate their account via email. * userAccount.EmailConfirmed = true; * * // Create user role * var findUserRole = await _roleManager.FindByNameAsync(role); * var userRole = new IdentityRole(role); * * // Add userAccount to a user role * if (!await _userManager.IsInRoleAsync(userAccount, userRole.Name)) * { * await _userManager.AddToRoleAsync(userAccount, userRole.Name); * } * return new OkResult(); * } * * // If result is not successful, add error message(s) * AddErrors(result); * * return new BadRequestObjectResult(result.Errors);*/ // } return(Ok()); }
public async Task Invoke(HttpContext httpContext, ContractMethodBinding binding) { if (httpContext.Request.ContentType == null && httpContext.Request.ContentLength != 0) { httpContext.Response.StatusCode = (int)HttpStatusCode.UnsupportedMediaType; return; } IInvocationSerializer requestSerializer = null; if (httpContext.Request.ContentType != null && !invocationSerializers.TryGetValue(httpContext.Request.ContentType, out requestSerializer)) { httpContext.Response.StatusCode = (int)HttpStatusCode.UnsupportedMediaType; return; } IInvocationSerializer responseSerializer = null; StringValues acceptHeader = httpContext.Request.Headers["Accept"]; if (acceptHeader.Count == 0 || (acceptHeader.Count == 1 && acceptHeader[0] == "*/*")) { // Use request serializer or use the first one resolved responseSerializer = requestSerializer ?? invocationSerializers.Values.First(); } else if (!acceptHeader.Any(value => invocationSerializers.TryGetValue(value, out responseSerializer))) { httpContext.Response.StatusCode = (int)HttpStatusCode.NotAcceptable; return; } ArgumentDictionary arguments; Dictionary <string, Type> argumentMapping = binding.ContractMethodInfo.GetParameters().ToDictionary(x => x.Name, x => x.ParameterType); if (httpContext.Request.ContentLength != 0) { arguments = await requestSerializer.DeserializeArgumentsAsync(httpContext.Request.Body, argumentMapping); } else { arguments = new ArgumentDictionary(); } object contractImplementation = contractImplementationResolver.Resolve(binding.ContractType); AuthorizationContext authorizationContext = await authorizationContextProvider.GetAuthorizationContextAsync(contractImplementation, binding.ContractMethodInfo); if (!await authorizationHandler.AuthorizeAsync(httpContext, authorizationContext)) { return; } var result = await methodInvoker.InvokeAsync(binding.ContractMethodInfo, contractImplementation, arguments.Values.ToArray()); if (result == null) { httpContext.Response.StatusCode = (int)HttpStatusCode.NoContent; return; } else if (responseSerializer != null) { httpContext.Response.ContentType = responseSerializer.MediaType; httpContext.Response.StatusCode = (int)HttpStatusCode.OK; await responseSerializer.SerializeAsync(httpContext.Response.Body, result.GetType(), result); } else { httpContext.Response.StatusCode = (int)HttpStatusCode.NotAcceptable; return; } }
public async Task <ActionResult> GetInstances( string org, string appId, [FromQuery(Name = "process.currentTask")] string currentTaskId, [FromQuery(Name = "process.isComplete")] bool?processIsComplete, [FromQuery(Name = "process.isInError")] bool?processIsInError, [FromQuery(Name = "process.endState")] string processEndState, [FromQuery] int?instanceOwnerId, [FromQuery] string labels, [FromQuery] string lastChangedDateTime, [FromQuery] string createdDateTime, [FromQuery] string visibleDateTime, [FromQuery] string dueDateTime, string continuationToken, int?size) { int pageSize = size ?? 100; string selfContinuationToken = null; if (!string.IsNullOrEmpty(continuationToken)) { selfContinuationToken = continuationToken; continuationToken = HttpUtility.UrlDecode(continuationToken); } Dictionary <string, StringValues> queryParams = QueryHelpers.ParseQuery(Request.QueryString.Value); string host = $"{Request.Scheme}://{Request.Host.ToUriComponent()}"; string url = Request.Path; string query = Request.QueryString.Value; logger.LogInformation($"uri = {url}{query}"); try { InstanceQueryResponse result = await _instanceRepository.GetInstancesOfApplication(queryParams, continuationToken, pageSize); if (result.TotalHits == 0) { return(NotFound($"Did not find any instances")); } if (!string.IsNullOrEmpty(result.Exception)) { return(BadRequest(result.Exception)); } string nextContinuationToken = HttpUtility.UrlEncode(result.ContinuationToken); result.ContinuationToken = null; HALResponse response = new HALResponse(result); if (continuationToken == null) { string selfUrl = $"{host}{url}{query}"; result.Self = selfUrl; Link selfLink = new Link("self", selfUrl); response.AddLinks(selfLink); } else { string selfQueryString = BuildQueryStringWithOneReplacedParameter( queryParams, "continuationToken", selfContinuationToken); string selfUrl = $"{host}{url}{selfQueryString}"; result.Self = selfUrl; Link selfLink = new Link("self", selfUrl); response.AddLinks(selfLink); } if (nextContinuationToken != null) { string nextQueryString = BuildQueryStringWithOneReplacedParameter( queryParams, "continuationToken", nextContinuationToken); string nextUrl = $"{host}{url}{nextQueryString}"; result.Next = nextUrl; Link nextLink = new Link("next", nextUrl); response.AddLinks(nextLink); } // add self links to platform result.Instances.ForEach(i => AddSelfLinks(Request, i)); StringValues acceptHeader = Request.Headers["Accept"]; if (acceptHeader.Any() && acceptHeader.Contains("application/hal+json")) { /* Response object should be expressed as HAL (Hypertext Application Language) with _embedded and _links. * Thus we reset the response object's inline instances, next and self elements.*/ response.AddEmbeddedCollection("instances", result.Instances); result.Instances = null; result.Next = null; result.Self = null; } return(Ok(response)); } catch (Exception e) { logger.LogError("exception", e); return(StatusCode(500, $"Unable to perform query due to: {e.Message}")); } }
public bool CanTransform(HttpRequestRecord record, StringValues contentTypeHeaderValues) { return(contentTypeHeaderValues.Any(x => x == "application/x-msgpack")); }
private async Task HandleExceptionAsync(HttpContext context, Exception exc) { if (exc is AggregateException) { exc = exc.InnerException; } logger.LogError(exc.ToString()); string errorMsg = logOptions.ShowErrorDetailsInResponse ? exc.ToString() : Constant.DefaultErrorMsg; StringValues stringValues = context.Request.Headers[Constant.Protocol]; Guid protocol; if (stringValues != StringValues.Empty && stringValues.Any()) { Guid.TryParse(stringValues.FirstOrDefault(), out protocol); } else { protocol = Guid.NewGuid(); context.Request.Headers.Add(Constant.Protocol, protocol.ToString()); } if (logOptions.EnableLogError) { IErrorLogger customErrorLogger = context.RequestServices.GetService <IErrorLogger>(); try { if (customErrorLogger == null) { if (!string.IsNullOrWhiteSpace(logOptions.DirectoryToLogErrorsOnFail)) { if (!Directory.Exists(logOptions.DirectoryToLogErrorsOnFail)) { Directory.CreateDirectory(logOptions.DirectoryToLogErrorsOnFail); } File.AppendAllText(Path.Combine(logOptions.DirectoryToLogErrorsOnFail, $"LogError-{DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")}.txt"), exc.ToString()); } } else { string loggedUser = context?.User?.Identity?.Name; string ipCliente = accessor?.HttpContext?.Connection?.RemoteIpAddress?.ToString(); string requestUrl = Microsoft.AspNetCore.Http.Extensions.UriHelper.GetDisplayUrl(context.Request); if (logOptions.LogErrorInBackground) { customErrorLogger.LogAsync(exc, protocol, loggedUser, ipCliente, requestUrl, context.Request.Method, context); } else { Result resultLog = await customErrorLogger.LogAsync(exc, protocol, loggedUser, ipCliente, requestUrl, context.Request.Method, context); if (!resultLog.Valid && !string.IsNullOrWhiteSpace(logOptions.DirectoryToLogErrorsOnFail)) { LogFailInFile(exc, JsonConvert.SerializeObject(resultLog, Formatting.Indented)); } } } } catch (Exception logExc) { if (!string.IsNullOrWhiteSpace(logOptions.DirectoryToLogErrorsOnFail)) { LogFailInFile(exc, logExc.ToString()); } if (!logOptions.IgnoreExceptionsOccuredInLogProcess) { throw; } } } if (string.IsNullOrWhiteSpace(logOptions.RedirectToPageIfIsNotAjaxRequest)) { var result = new Result { Protocol = protocol }; result.Set(ResultCode.GenericError, errorMsg); string resultJson = JsonConvert.SerializeObject(result); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)result.ResultCode; await context.Response.WriteAsync(resultJson); } else { if (context.Request.IsAjaxRequest()) { var result = new Result { Protocol = protocol }; result.Set(ResultCode.GenericError, errorMsg); string resultJson = JsonConvert.SerializeObject(result); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)result.ResultCode; await context.Response.WriteAsync(resultJson); } else { context.Response.Redirect(logOptions.RedirectToPageIfIsNotAjaxRequest, true); } } }