public async Task Invoke(HttpContext context) { try { await next(context); if (context.Response.StatusCode >= 400) { var code = context.Response.StatusCode; logger.LogWarning($"Code:{code} Reason:{ReasonPhrases.GetReasonPhrase(code)}"); } } catch (Exception e) { logger.LogError(e, "Exception"); throw; } }
public IActionResult StatusCodeGet(int statusCode) { if (400 <= statusCode && statusCode < 600) { var model = new StatusCodeViewModel { StatusCode = statusCode, ReasonPhrase = ReasonPhrases.GetReasonPhrase(statusCode) }; HttpContext.Response.StatusCode = statusCode; return(View("StatusCode", model)); } else { return(Redirect("/")); } }
void ProduceStart() { if (_resultStarted) { return; } _resultStarted = true; var status = ReasonPhrases.ToStatus( Get("owin.ResponseStatusCode", 200), Get <string>("owin.ResponseReasonPhrase")); var responseHeader = CreateResponseHeader(status, _responseHeaders); _context.Write(responseHeader.Item1); responseHeader.Item2.Dispose(); }
public unsafe void SendResponseHeaders(bool appCompleted) { // Verifies we have sent the statuscode before writing a header var reasonPhraseBytes = Encoding.UTF8.GetBytes(ReasonPhrase ?? ReasonPhrases.GetReasonPhrase(StatusCode)); fixed(byte *pReasonPhrase = reasonPhraseBytes) { // This copies data into the underlying buffer NativeMethods.http_set_response_status_code(_pInProcessHandler, (ushort)StatusCode, pReasonPhrase); } HttpResponseHeaders.IsReadOnly = true; foreach (var headerPair in HttpResponseHeaders) { var headerValues = headerPair.Value; var knownHeaderIndex = HttpApiTypes.HTTP_RESPONSE_HEADER_ID.IndexOfKnownHeader(headerPair.Key); if (knownHeaderIndex == -1) { var headerNameBytes = Encoding.UTF8.GetBytes(headerPair.Key); for (var i = 0; i < headerValues.Count; i++) { var headerValueBytes = Encoding.UTF8.GetBytes(headerValues[i]); fixed(byte *pHeaderName = headerNameBytes) { fixed(byte *pHeaderValue = headerValueBytes) { NativeMethods.http_response_set_unknown_header(_pInProcessHandler, pHeaderName, pHeaderValue, (ushort)headerValueBytes.Length, fReplace: false); } } } } else { for (var i = 0; i < headerValues.Count; i++) { var headerValueBytes = Encoding.UTF8.GetBytes(headerValues[i]); fixed(byte *pHeaderValue = headerValueBytes) { NativeMethods.http_response_set_known_header(_pInProcessHandler, knownHeaderIndex, pHeaderValue, (ushort)headerValueBytes.Length, fReplace: false); } } } } }
private void Default(ref WritableBuffer outputBuffer) { var writer = new WritableBufferWriter(outputBuffer); // HTTP 1.1 OK writer.Write(_bytesHttpVersion11); writer.Write(ReasonPhrases.ToStatusBytes(200, reasonPhrase: null)); // Headers var values = _dateHeaderValueManager.GetDateHeaderValues(); ResponseHeaders.SetRawDate(values.String, values.Bytes); ResponseHeaders.SetRawServer("Custom", _headerServer); ResponseHeaders.ContentLength = 0; // Write headers ResponseHeaders.CopyTo(ref writer); writer.Write(_bytesEndHeaders); }
public IActionResult StatusCodeHandler(int code) { ViewBag.StatusCode = code; ViewBag.StatusCodeDescription = ReasonPhrases.GetReasonPhrase(code); ViewBag.OriginalUrl = null; var statusCodeReExecuteFeature = HttpContext.Features.Get <IStatusCodeReExecuteFeature>(); if (statusCodeReExecuteFeature != null) { ViewBag.OriginalUrl = statusCodeReExecuteFeature.OriginalPathBase + statusCodeReExecuteFeature.OriginalPath + statusCodeReExecuteFeature.OriginalQueryString; } return(View(code == 404 ? "Status404" : "Status4xx")); }
public async Task StatusCodePageOptions_IncludesSemicolon__AndReasonPhrase_WhenReasonPhrase_IsKnown() { //Arrange var httpStatusCode = 400; var request = new HttpRequestMessage(HttpMethod.Get, $"http://localhost/?statuscode={httpStatusCode}"); //Act var response = await Client.SendAsync(request); var statusCode = response.StatusCode; var statusCodeReasonPhrase = ReasonPhrases.GetReasonPhrase(httpStatusCode); var responseBody = await response.Content.ReadAsStringAsync(); //Assert Assert.Equal((HttpStatusCode)httpStatusCode, response.StatusCode); Assert.Contains(";", responseBody); Assert.Contains(statusCodeReasonPhrase, responseBody); }
void ProduceStart() { if (_resultStarted) { return; } _resultStarted = true; var response = (IHttpResponseFeature)_callContext; var status = ReasonPhrases.ToStatus( response.StatusCode, response.ReasonPhrase); var responseHeader = CreateResponseHeader(status, _responseHeaders); _context.Write(responseHeader.Item1); responseHeader.Item2.Dispose(); }
public IActionResult HttpError(int?statusCode) { var statusMessage = string.Empty; switch (statusCode) { case 400: statusMessage = GlobalConstants.ErrorStatusBadRequest; break; case 403: statusMessage = GlobalConstants.ErrorStatusForbidden; break; case 404: statusMessage = GlobalConstants.ErrorStatusPageNotFound; break; case 408: statusMessage = GlobalConstants.ErrorStatusTimeout; break; case 500: statusMessage = GlobalConstants.ErrorStatusInternalServerError; break; default: statusMessage = GlobalConstants.ErrorStatusOther; break; } string reasonPhrase = ReasonPhrases.GetReasonPhrase(statusCode.Value); var viewModel = new CustomErrorViewModel { StatusCodeNumber = statusCode.Value, ReasonPhrase = reasonPhrase, StatusMessage = statusMessage, }; return(this.View(viewModel)); }
public void SetProblemDetails(ProblemDetails problemDetails, int statusCode) { problemDetails.Instance = this._requestPath; problemDetails.Status = statusCode; var traceId = Activity.Current?.Id ?? _traceId; problemDetails.Extensions[TRACE_IDENTIFIER_KEY] = traceId; if (ClientErrorMapping.TryGetValue(statusCode, out var errorData)) { problemDetails.Title = errorData.Title; problemDetails.Type = errorData.Link; } else { problemDetails.Type = string.Format(STATUS_CODE_TYPE_URI, statusCode); problemDetails.Title = ReasonPhrases.GetReasonPhrase(statusCode); } }
internal async Task HandleUncaughtException(HttpContext context) { var exceptionHandlerPathFeature = context.Features.Get <IExceptionHandlerPathFeature>(); var path = exceptionHandlerPathFeature?.Path; var error = exceptionHandlerPathFeature?.Error; Log.Error(error, "Unhandled error: {path}", path); var statusCode = (int)HttpStatusCode.InternalServerError; context.Response.StatusCode = statusCode; context.Response.ContentType = "application/json"; await context.Response.WriteAsync( string.Format( "{{ \"code\":{0}, \"reason\":\"{1}\" }}", statusCode, ReasonPhrases.GetReasonPhrase(statusCode))); }
public static IApplicationBuilder ConfigureStatusCodePages(this IApplicationBuilder app) { app.UseStatusCodePages(appBuilder => { appBuilder.Run(async httpContext => { httpContext.Response.ContentType = "application/json"; var statusCodeDetails = new StatusCodeDetails { StatusCode = httpContext.Response.StatusCode, Message = ReasonPhrases.GetReasonPhrase(httpContext.Response.StatusCode) }; await httpContext.Response.WriteAsync(statusCodeDetails.ToJsonString()); }); }); return(app); }
public async Task ProblemDetailsException_IsHandled() { const int expected = StatusCodes.Status429TooManyRequests; var details = new MvcProblemDetails { Title = ReasonPhrases.GetReasonPhrase(expected), Type = $"https://httpstatuses.com/{expected}", Status = expected, }; var ex = new ProblemDetailsException(details); using var client = CreateClient(handler: ResponseThrows(ex)); var response = await client.GetAsync("/"); Assert.Equal(expected, (int)response.StatusCode); await AssertIsProblemDetailsResponse(response, expectExceptionDetails : false); }
public async Task Invoke(HttpContext httpContext) { httpContext.Response.OnStarting(() => { if (httpContext.Response.StatusCode == 405) { httpContext.Response.ContentType = "application/json"; string msg = ReasonPhrases.GetReasonPhrase(httpContext.Response.StatusCode); return(httpContext.Response.WriteAsync(new ErrorDetails() { Status = httpContext.Response.StatusCode, Title = msg, Message = msg }.ToString())); } return(Task.CompletedTask); }); await _next(httpContext); GC.Collect(2, GCCollectionMode.Forced, true); GC.WaitForPendingFinalizers(); }
public async Task <Response> Delete(string domain) { var request = new Request { Url = $"/api/{client.Version}/sending-domains/{domain}", Method = "DELETE", }; var response = await requestSender.Send(request); if (response.StatusCode == HttpStatusCode.NoContent) { response.StatusCode = HttpStatusCode.OK; response.ReasonPhrase = ReasonPhrases.GetReasonPhrase((int)response.StatusCode); } if (response.StatusCode != HttpStatusCode.OK) { throw new ResponseException(response); } return(response); }
public async Task InvokeAsync(HttpContext context) { using (var memoryStream = new MemoryStream()) { ApiResponse result = null; if (!IsSwagger(context)) { var currentBody = context.Response.Body; context.Response.Body = memoryStream; try { await _next(context); result = new ApiResponse( success: true, code: context.Response.StatusCode, message: ApiResponse.UserResponseMessage ?? (context.Response.StatusCode >= 300 ? ReasonPhrases.GetReasonPhrase(context.Response.StatusCode) : null), data: GetResponseObject(context, memoryStream, currentBody)); } catch (Exception ex) { result = new ApiResponse( success: false, code: context.Response.StatusCode, message: $"Unhandled exception: {ex.GetType().Name}, message: {ex.Message}", data: GetResponseObject(context, memoryStream, currentBody)); } await context.Response.WriteAsync(JsonConvert.SerializeObject(result)); } else { await _next(context); } } ApiResponse.UserResponseMessage = null; }
public async Task InvokeAsync(HttpContext context, RequestDelegate next) { try { await next(context); } catch (Exception ex) { var statusCode = GetStatusCode(ex); var problemDetails = new ProblemDetails { Status = statusCode, Title = ReasonPhrases.GetReasonPhrase(statusCode), Type = $"https://httpstatuses.com{statusCode}", Detail = ex is Core.Exceptions.ValidationException ? ex.Message : default }; context.Response.ContentType = "application/json"; context.Response.StatusCode = statusCode; await context.Response.WriteAsync(JsonConvert.SerializeObject(problemDetails, _jsonSerializerSettings)); } }
public async Task <ActionResult <dynamic> > Testea(string serverId, string videoId) { var response = await _videosServices.GetVideo(serverId, videoId); if (!response.Success) { return(BadRequest(new ProblemDetails() { Type = "https://httpstatuses.com/400", Title = ReasonPhrases.GetReasonPhrase(400), Status = 400, Detail = response.Message })); } var encoded = Regex.Replace(response.Video.VideoBase64, @"data:video\/.{3,7};base64,", String.Empty); encoded = encoded.Replace("data:application/pdf;base64,", String.Empty); var type = Regex.Replace(response.Video.VideoBase64, @";.*", String.Empty); var contentType = type.Replace("data:", ""); byte[] ret = Convert.FromBase64String(encoded); return(File(ret, contentType)); }
/// <summary> /// Format the exception as a problem details. /// </summary> /// <returns></returns> public virtual ProblemDetails ToProblemDetails() { var details = CreateProblemDetails(); details.Type = "about:blank"; details.Title = ReasonPhrases.GetReasonPhrase(StatusCode); details.Status = StatusCode; details.Detail = Message; ErrorCodeHelpAttribute attr = ErrorCode.GetType() .GetMember(ErrorCode.ToString()) .Where(m => m.MemberType == MemberTypes.Field) .FirstOrDefault() ?.GetCustomAttribute <ErrorCodeHelpAttribute>(); if (attr != null) { details.Title = attr.Title; details.Type = attr.ResolveUrl(); } return(details); }
/// <summary> /// Handles exception formatting and logging. /// </summary> /// <param name="ex"></param> /// <param name="context"></param> /// <param name="details"></param> /// <returns></returns> private bool TryHandleException(Exception ex, HttpContext context, out ProblemDetails details) { //keep a reference to original exception prior to adapt any convertion/formatting Exception exToFormat = ex ?? throw new ArgumentNullException(nameof(ex)); //apply common rules for well-known exceptions convertible to an ApiException with its associated error code switch (exToFormat) { //add case based on exception type when specific rules are required case ApiException _: default: //exception is already formattable as is, or we do not have any convertion yet break; } details = null; if (exToFormat is ApiException apiException) { details = apiException.ToProblemDetails(); } else { LogException(exToFormat, context); //format unknow exceptions as problem details details = new ProblemDetails() { Type = "about:blank", Title = ReasonPhrases.GetReasonPhrase(StatusCodes.Status500InternalServerError), Status = StatusCodes.Status500InternalServerError, Detail = "An error occurred while executing the request" }; } return(details != null); }
/// <summary> /// Constructor, defaults to a 404 response /// </summary> public MockResponse(int Status = StatusCodes.Status400BadRequest, string Body = null, IDictionary <string, string> Headers = null, IDictionary <string, string> Queries = null, ResponseType?responseType = ResponseType.CUSTOM) { if (Body == null) { Body = ReasonPhrases.GetReasonPhrase(StatusCodes.Status400BadRequest); } if (Headers == null) { Headers = new Dictionary <string, string>(); } if (Queries == null) { Queries = new Dictionary <string, string>(); } this.Status = Status; this.Body = Body; this.Headers = Headers; this.Queries = Queries; this.Type = responseType ?? ResponseType.CUSTOM; }
public async Task <string> GetFromDockerServiceAsync(string serviceName, int port, string path, Dictionary <string, string> data) { try { var requestParams = string.Join('&', data.Select(cur => $"{cur.Key}={cur.Value}")); var requestPath = new StringBuilder($"http://{serviceName}:{port}{path}"); if (!string.IsNullOrEmpty(requestParams)) { requestPath.Append("?").Append(requestParams); } var serviceResponse = await _client.GetAsync(requestPath.ToString()); var serviceMessage = serviceResponse.IsSuccessStatusCode ? await serviceResponse.Content.ReadAsStringAsync() : $"Some error occured, reason: {ReasonPhrases.GetReasonPhrase((int)serviceResponse.StatusCode)}"; return(serviceMessage); } catch (Exception ex) { return($"Unhandled exception: {ex.GetType().Name}, message: {ex.Message}"); } }
/// <inheritdoc/> public override ProblemDetails CreateProblemDetails(HttpContext httpContext, int?statusCode = null, string?title = null, string?type = null, string?detail = null, string?instance = null) { statusCode ??= (int)HttpStatusCode.InternalServerError; title ??= ReasonPhrases.GetReasonPhrase(statusCode.Value); var context = httpContext.Features.Get <IExceptionHandlerFeature>(); if (context?.Error != null) { detail ??= context.Error?.Message; } var problemDetails = new ProblemDetails { Detail = detail, Instance = instance, Status = statusCode, Title = title, Type = type }; return(ApplyProblemDetailsDefaults(httpContext, problemDetails)); }
public static async ValueTask StatuscodeSetter(HttpContext context, Exception err = null) { err = err ?? context.Features.Get <IExceptionHandlerPathFeature>().Error; context.Response.StatusCode = err switch { HttpException e => e.StatusCode, _ => StatusCodes.Status500InternalServerError, }; var limfxErr = new LimFxError() { title = ReasonPhrases.GetReasonPhrase(context.Response.StatusCode), status = context.Response.StatusCode, traceId = context.TraceIdentifier, errors = new Dictionary <string, string> { { "errorMessage", context.Response.StatusCode == StatusCodes.Status500InternalServerError ? "internal server error!" : err.Message } } }; context.Response.ContentType = MediaTypeNames.Application.Json; await context.Response.WriteAsync(JsonSerializer.Serialize(limfxErr)); await context.Response.WriteAsync(new string(' ', 512)); // IE padding }
public void OnGet(int?errorCode) { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; ErrorCode = errorCode ?? HttpContext.Response.StatusCode; ErrorMessage = ReasonPhrases.GetReasonPhrase(ErrorCode.GetValueOrDefault()); }
/// <inheritdoc /> /// <summary> /// Returns the gradebook columns in a course. /// </summary> /// <returns>Line items corresponding to the gradebook columns.</returns> protected override async Task <ActionResult <LineItemContainer> > OnGetLineItemsAsync(GetLineItemsRequest request) { if (!int.TryParse(request.ContextId, out var contextId)) { var name = $"{nameof(request)}.{nameof(request.ContextId)}"; ModelState.AddModelError(name, $"The {name} field cannot be converted into a course id."); return(BadRequest(new ValidationProblemDetails(ModelState))); } if (!await _courseValidator.UserHasAccess(contextId)) { return(Unauthorized(new ProblemDetails { Title = "Not authorized", Detail = "User not authorized to access the requested course." })); } var course = await _context.GetCourseAsync(contextId); if (course == null) { return(NotFound(new ProblemDetails { Title = ReasonPhrases.GetReasonPhrase(StatusCodes.Status404NotFound), Detail = "Course not found" })); } var lineitems = new List <LineItem>(); foreach (var gradebookColumn in course.GradebookColumns) { lineitems.Add(new LineItem { Id = Url.Link(LtiAdvantage.Constants.ServiceEndpoints.Ags.LineItemService, new { contextId = request.ContextId, lineItemId = gradebookColumn.Id }), EndDateTime = gradebookColumn.EndDateTime, Label = gradebookColumn.Label, ResourceId = gradebookColumn.ResourceId, ResourceLinkId = gradebookColumn.ResourceLink.Id.ToString(), ScoreMaximum = gradebookColumn.ScoreMaximum, StartDateTime = gradebookColumn.StartDateTime, Tag = gradebookColumn.Tag }); } if (request.ResourceId.IsPresent()) { lineitems = lineitems.Where(l => l.ResourceId == request.ResourceId).ToList(); } if (request.ResourceLinkId.IsPresent()) { lineitems = lineitems.Where(l => l.ResourceLinkId == request.ResourceLinkId).ToList(); } if (request.Tag.IsPresent()) { lineitems = lineitems.Where(l => l.Tag == request.Tag).ToList(); } return(new LineItemContainer(lineitems)); }
/// <summary> /// Get Xml element with status description /// </summary> /// <param name="ns">Namespace</param> /// <param name="statusCode">Status code</param> /// <returns></returns> public static XElement GetStatus(XNamespace ns, HttpStatusCode statusCode) { var reasonPhrases = ReasonPhrases.GetReasonPhrase((int)statusCode); return(GetElement(ns, "status", $"HTTP/1.1 {(int)statusCode} {reasonPhrases}")); }
public IActionResult ErroGenerico(int statusCode) { ViewBag.StatusCode = statusCode; ViewBag.Mensagem = ReasonPhrases.GetReasonPhrase(statusCode); return(View()); }
/// <inheritdoc /> /// <summary> /// Updates a line item. /// </summary> protected override async Task <ActionResult> OnUpdateLineItemAsync(UpdateLineItemRequest request) { if (!int.TryParse(request.ContextId, out var contextId)) { var name = $"{nameof(request)}.{nameof(request.ContextId)}"; ModelState.AddModelError(name, $"The {name} field cannot be converted into a course id."); } if (!int.TryParse(request.LineItemId, out var lineItemId)) { var name = $"{nameof(request)}.{nameof(request.LineItemId)}"; ModelState.AddModelError(name, $"The {name} field cannot be converted into a gradebook column id."); } if (!ModelState.IsValid) { return(BadRequest(new ValidationProblemDetails(ModelState))); } if (!await _courseValidator.UserHasAccess(contextId)) { return(Unauthorized(new ProblemDetails { Title = "Not authorized", Detail = "User not authorized to access the requested course." })); } var course = await _context.GetCourseAsync(contextId); if (course == null) { return(NotFound(new ProblemDetails { Title = ReasonPhrases.GetReasonPhrase(StatusCodes.Status404NotFound), Detail = "Course not found" })); } if (course.GradebookColumns.All(c => c.Id != lineItemId)) { return(NotFound(new ProblemDetails { Title = ReasonPhrases.GetReasonPhrase(StatusCodes.Status404NotFound), Detail = "Gradebook column not found" })); } var gradebookColumn = await _context.GetGradebookColumnAsync(lineItemId); gradebookColumn.EndDateTime = request.LineItem.EndDateTime; gradebookColumn.Label = request.LineItem.Label; gradebookColumn.ResourceId = request.LineItem.ResourceId; gradebookColumn.ScoreMaximum = request.LineItem.ScoreMaximum; gradebookColumn.StartDateTime = request.LineItem.StartDateTime; gradebookColumn.Tag = request.LineItem.Tag; if (request.LineItem.ResourceLinkId.IsPresent()) { if (!int.TryParse(request.LineItem.ResourceLinkId, out var resourceLinkId)) { var name = $"{nameof(request)}.{nameof(request.LineItem)}.{request.LineItem.ResourceLinkId}"; ModelState.AddModelError(name, $"The {name} field cannot be converted into a valid resource link id."); return(BadRequest(new ValidationProblemDetails(ModelState))); } var resourceLink = await _context.GetResourceLinkAsync(resourceLinkId); if (resourceLink == null) { var name = $"{nameof(request)}.{nameof(request.LineItem)}.{request.LineItem.ResourceLinkId}"; ModelState.AddModelError(name, $"The {name} field is not a valid resource link id."); return(BadRequest(new ValidationProblemDetails(ModelState))); } gradebookColumn.ResourceLink = resourceLink; } else { gradebookColumn.ResourceLink = null; } _context.GradebookColumns.Update(gradebookColumn); await _context.SaveChangesAsync(); return(NoContent()); }
/// <inheritdoc /> /// <summary> /// Adds a gradebook column to a course. /// </summary> /// <returns>The line item corresponding to the new gradebook column.</returns> protected override async Task <ActionResult <LineItem> > OnAddLineItemAsync(AddLineItemRequest request) { if (!int.TryParse(request.ContextId, out var contextId)) { var name = $"{nameof(request)}.{nameof(request.ContextId)}"; ModelState.AddModelError(name, $"The {name} field cannot be converted into a course id."); return(BadRequest(new ValidationProblemDetails(ModelState))); } if (!await _courseValidator.UserHasAccess(contextId)) { return(Unauthorized(new ProblemDetails { Title = "Not authorized", Detail = "User not authorized to access the requested course." })); } var course = await _context.GetCourseAsync(contextId); if (course == null) { return(NotFound(new ProblemDetails { Title = ReasonPhrases.GetReasonPhrase(StatusCodes.Status404NotFound), Detail = "Course not found" })); } // Add a gradebook column to the course var gradebookColumn = new GradebookColumn { EndDateTime = request.LineItem.EndDateTime, Label = request.LineItem.Label, ScoreMaximum = request.LineItem.ScoreMaximum, StartDateTime = request.LineItem.StartDateTime, Tag = request.LineItem.Tag }; if (request.LineItem.ResourceLinkId.IsPresent()) { if (!int.TryParse(request.LineItem.ResourceLinkId, out var resourceLinkId)) { var name = $"{nameof(request)}.{nameof(request.LineItem.ResourceLinkId)}"; ModelState.AddModelError(name, $"The {name} field cannot be converted into a resource link id."); return(BadRequest(new ValidationProblemDetails(ModelState))); } var resourceLink = await _context.GetResourceLinkAsync(resourceLinkId); if (resourceLink == null) { var name = $"{nameof(request)}.{nameof(request.LineItem)}.{request.LineItem.ResourceLinkId}"; ModelState.AddModelError(name, $"The {name} field is not a valid resource link id."); return(BadRequest(new ValidationProblemDetails(ModelState))); } gradebookColumn.ResourceLink = resourceLink; } course.GradebookColumns.Add(gradebookColumn); await _context.SaveChangesAsync(); request.LineItem.Id = Url.Link(LtiAdvantage.Constants.ServiceEndpoints.Ags.LineItemService, new { contextId = request.ContextId, lineItemId = gradebookColumn.Id }); return(Created(request.LineItem.Id, request.LineItem)); }