public static Task WriteStatusCodeResponse(this HttpContext context, int?statusCode = null) { Log.Information("Writing Status Code Response | specified: {0} | context: {1} | hasStarted: {2}", statusCode, context.Response.StatusCode, context.Response.HasStarted); context.Response.ContentType = "application/json"; if (!statusCode.HasValue) { statusCode = context.Response.StatusCode; } else { context.Response.StatusCode = statusCode.Value; } string statusCodeText = ReasonPhrases.GetReasonPhrase(statusCode.Value); var problemDetails = new ProblemDetails() { Status = statusCode.Value, Title = statusCodeText }; var ignoreNullValues = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; string serialized = JsonConvert.SerializeObject(problemDetails, Formatting.None, ignoreNullValues); return(context.Response.WriteAsync(serialized)); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger, IConfiguration configuration) { app.Run(context => { return(context.Response.WriteAsync($"{ReasonPhrases.GetReasonPhrase(200)} : {ReasonPhrases.GetReasonPhrase(500)}")); }); }
public void ConfigureServices(IServiceCollection services) { services.AddReverseProxy().LoadFromConfig(configuration); services.AddPercolatorLogic() .AddPercolatorApi() .AddPercolatorStorage(); services.AddControllers(); services.AddProblemDetails(opt => { opt.IncludeExceptionDetails = (_, _) => environment.IsDevelopment(); MapExceptions(opt); }); services.Configure <ApiBehaviorOptions>(opt => { opt.ClientErrorMapping.Clear(); foreach (int statusCode in Enum.GetValues(typeof(System.Net.HttpStatusCode))) { opt.ClientErrorMapping[statusCode] = new ClientErrorData { Link = $"https://httpstatuses.com/{statusCode}", Title = ReasonPhrases.GetReasonPhrase(statusCode), }; } }); services.AddHealthChecks(); services.Configure <InMemoryFilterRepositorySettings>(configuration.GetSection($"Storage:{nameof(InMemoryFilterRepositorySettings)}")); }
public IActionResult ErroGenerico(int statusCode) { ViewBag.StatusCode = statusCode; ViewBag.Mensagem = ReasonPhrases.GetReasonPhrase(statusCode); return(View()); }
public async Task InvokeAsync(HttpContext context) { try { await _next(context); _logger.LogError(ReasonPhrases.GetReasonPhrase(context.Response.StatusCode)); } catch (Exception ex) { _logger.LogError(ex, ex.Message); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; var response = _env.IsDevelopment() ? new ApiException(context.Response.StatusCode, ex.Message, ex.StackTrace?.ToString()) : new ApiException(context.Response.StatusCode, "Internal Server Error"); var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; // _logger.LogError(context.Response.ToString()); var json = JsonSerializer.Serialize(response, options); await context.Response.WriteAsync(json); } }
public IActionResult Index(int code) { ViewData["code"] = code; ViewData["description"] = ReasonPhrases.GetReasonPhrase(code); return(View()); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { using (var context = new WordContext()) { context.Database.Migrate(); } app.UseResponseCompression(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStatusCodePages(async ctx => { ctx.HttpContext.Response.ContentType = "text/html"; int statusCode = ctx.HttpContext.Response.StatusCode; string statusDescription = ReasonPhrases.GetReasonPhrase(statusCode); await ctx.HttpContext.Response.WriteAsync("<html lang=\"ko\">"); await ctx.HttpContext.Response.WriteAsync("<head><style>body {text-align:center;} .desc{font-size:12pt;}</style></head>"); await ctx.HttpContext.Response.WriteAsync($"<body>\r\n<h1>{statusCode} {statusDescription}</h1>\r\n"); await ctx.HttpContext.Response.WriteAsync("<hr>\r\n"); await ctx.HttpContext.Response.WriteAsync($"<span class=\"desc\">{App.Version}</span>\r\n"); await ctx.HttpContext.Response.WriteAsync("</body></html>"); }); app.UseStaticFiles(); app.UseHttpsRedirection(); app.UseMvc(routes => { routes.MapRoute("default", "{action=index}", defaults: new { controller = "main" }); }); }
public async Task FulfillAsync(ResponseData response) { var responseHeaders = response.Headers?.ToDictionary(header => header.Key.ToLower(), header => header.Value) ?? new Dictionary <string, string>(); if (!string.IsNullOrEmpty(response.ContentType)) { responseHeaders["content-type"] = response.ContentType; } if (response.BodyData != null && !responseHeaders.ContainsKey("content-length")) { responseHeaders["content-length"] = response.BodyData.Length.ToString(); } try { await _client.SendAsync(new FetchFulfillRequestRequest { RequestId = InterceptionId, ResponseCode = (int)(response.Status ?? HttpStatusCode.OK), ResponsePhrase = ReasonPhrases.GetReasonPhrase((int)(response.Status ?? HttpStatusCode.OK)), ResponseHeaders = responseHeaders.Select(kv => new HeaderEntry { Name = kv.Key.ToLower(), Value = kv.Value }).ToArray(), Body = response.BodyData, }).ConfigureAwait(false); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } }
public void ToString_UsesDefaultPhrase_WhenPhraseIsNull(int code) { var expectedResponse = $"HTTP {code} {ReasonPhrases.GetReasonPhrase(code)}"; var response = new ApiResponse(code, reasonPhrase: null); response.ToString().ShouldBe(expectedResponse); }
public void Configure(IApplicationBuilder app) { app.Run(context => { return(context.Response.WriteAsync($"{ReasonPhrases.GetReasonPhrase(200)} : {ReasonPhrases.GetReasonPhrase(500)}")); }); }
public void OnGet(int?code) { if (code is not null) { Code = (int)code; Name = ReasonPhrases.GetReasonPhrase((int)code); } else { Code = 0; Name = "Unknown Error"; } var statusCodeReExecuteFeature = HttpContext.Features.Get <IStatusCodeReExecuteFeature>(); if (statusCodeReExecuteFeature != null) { OriginalUrl = $"{Request.Scheme}://{Request.Host}" + statusCodeReExecuteFeature.OriginalPathBase + statusCodeReExecuteFeature.OriginalPath + statusCodeReExecuteFeature.OriginalQueryString; } Text = code switch {
private static Task HandleExceptionAsync(HttpContext httpContext, Exception exception, Guid xid, bool show_trace = true) { httpContext.Response.ContentType = "application/json"; httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; if (exception.Message.StartsWith("[") && exception.Message.EndsWith("]")) { return(httpContext.Response.WriteAsync(new ErrorDetails() { Status = httpContext.Response.StatusCode, Title = ReasonPhrases.GetReasonPhrase(httpContext.Response.StatusCode), Message = show_trace ? $"[{xid}] {exception.InnerException.Message}" : exception.InnerException.Message, Errors = new Dictionary <string, List <string> >() { { exception.Message.Split('[', ']')[1], new List <string>() { exception.InnerException.Message } } } }.ToString())); } return(httpContext.Response.WriteAsync(new ErrorDetails() { Status = httpContext.Response.StatusCode, Title = ReasonPhrases.GetReasonPhrase(httpContext.Response.StatusCode), Message = show_trace ? $"[{xid}] {exception.Message}" : exception.Message }.ToString())); }
public ApiProblemDetails(int statusCode) { IsError = true; Status = statusCode; Type = $"https://httpstatuses.com/{statusCode}"; Title = ReasonPhrases.GetReasonPhrase(statusCode); }
public async Task ProblemDetailsException_WithInnerException_InnerExceptionToBeIncludedInProblemDetailsExceptionDetails() { const int expected = StatusCodes.Status429TooManyRequests; var details = new MvcProblemDetails { Title = ReasonPhrases.GetReasonPhrase(expected), Type = $"https://httpstatuses.com/{expected}", Status = expected, }; const string innerExceptionMessage = "inner exception message"; var innerException = new ArgumentException(innerExceptionMessage); var ex = new ProblemDetailsException(details, innerException); using var client = CreateClient(handler: ResponseThrows(ex), SetOnBeforeWriteDetails); var response = await client.GetAsync(string.Empty); var responseProblemDetails = await response.Content.ReadFromJsonAsync <MvcProblemDetails>(); var responseExceptionDetails = (JsonElement)responseProblemDetails.Extensions[ProblemDetailsOptions.DefaultExceptionDetailsPropertyName]; var responseExceptionMessage = responseExceptionDetails.EnumerateArray().ToList()[0].GetProperty("message").GetString(); Assert.Equal(innerExceptionMessage, responseExceptionMessage); }
public HttpResultModel SetPropertyHttpResult(HttpResultModel httpResultModel, bool isSuccess = false, string title = "", string message = "", int statusCode = StatusCodes.Status200OK, dynamic objValue = null) { if (httpResultModel != null) { if (isSuccess) { httpResultModel.Title = !string.IsNullOrEmpty(title) ? $"{title} - {ReasonPhrases.GetReasonPhrase(statusCode)}" : $"{ReasonPhrases.GetReasonPhrase(statusCode)}"; httpResultModel.StatusCode = statusCode.ToString(); } else { httpResultModel.Title = $"API Error! - {ReasonPhrases.GetReasonPhrase(statusCode)}"; httpResultModel.StatusCode = statusCode.ToString(); } httpResultModel.Message = message; httpResultModel.Value = objValue; } else { httpResultModel = new HttpResultModel(); } return(httpResultModel); }
public void OnActionExecuted(ActionExecutedContext context) { if (context.Exception is NotImplementedException notImplemented) { _logger.Error(context.Exception, "Not implemented exception was thrown"); ErrorResponse response = new ErrorResponse(HttpStatusCode.NotImplemented, ReasonPhrases.GetReasonPhrase((int)HttpStatusCode.NotImplemented), notImplemented.Message); context.Result = new ObjectResult(response) { StatusCode = (int?)HttpStatusCode.NotImplemented }; context.ExceptionHandled = true; } else if (context.Exception is HttpResponseException httpResponse) { _logger.Error(context.Exception, "An unhandled exception was thrown"); ErrorResponse response = new ErrorResponse(httpResponse.Status, ReasonPhrases.GetReasonPhrase((int)httpResponse.Status), httpResponse.Value); context.Result = new ObjectResult(response) { StatusCode = (int?)httpResponse.Status }; context.ExceptionHandled = true; } else if (context.Exception != null) { _logger.Error(context.Exception, "An unhandled exception was thrown"); } }
public static string Format(HttpResponse response, string requestId, Stream bodyStream) { var text = string.Format( "RESPONSE #{4}\n" + "----------------------\n" + "{0} {1} {2}\n" + "Headers:\n{3}\n\n", response.StatusCode, ReasonPhrases.GetReasonPhrase(response.StatusCode), response.HttpContext.Features.Get <IHttpResponseFeature>()?.ReasonPhrase, // Custom reason phrase if it is defined FormatHeaders(response.Headers), requestId); if (bodyStream != null) { var body = new StreamReader(bodyStream).ReadToEnd(); if (!string.IsNullOrEmpty(body)) { text += $"Content:\n{body}\n\n"; } } else { text += $"Content:\n!!!REMOVED FROM LOG!!!\n\n"; } return(text); }
public IActionResult Default(int code, [FromQuery] string r) { ViewBag.Code = code; ViewBag.Message = ReasonPhrases.GetReasonPhrase(code); ViewBag.English = ReasonPhrases.GetReasonPhrase(code); ViewBag.Description = "Het schip lijkt op de klippen te zijn gelopen"; ViewBag.Redirect = (string.IsNullOrEmpty(r) ? null : r); this.HttpContext.Response.StatusCode = code; if (ViewBag.Message == "" || ViewBag.Message == null) { ViewBag.Message = "Er is iets fout gegaan"; } if (code == 400) { ViewBag.Message = "Bad Request"; ViewBag.Description = "We staan versteld van hoe jij dit doet!"; ViewBag.showHome = true; } else if (code == 401) { ViewBag.Message = "Niet ingelogd"; ViewBag.Description = "De kaptitein was er niet van op de hoogte dat u mee zou varen"; ViewBag.showLogin = true; ViewBag.showHome = true; } else if (code == 403) { ViewBag.Message = "Onvoldoende rechten"; ViewBag.Description = "De kaptitein verbiedt een matroos om hier te komen"; ViewBag.showLogin = true; } else if (code == 404) { ViewBag.Message = "Pagina niet gevonden"; ViewBag.Description = "<i>Oh, the lost his compass...</i>?<br>Het schip heeft een verkeerde route gevaren"; ViewBag.showHome = true; } else if (code == 418) { ViewBag.Message = "Ik ben een theepot!"; ViewBag.Description = "<i>Thee is best lekker als je ver moet varen</i>"; ViewBag.showHome = true; } else if (code == 500) { ViewBag.Message = "Interne serverfout"; ViewBag.Description = "<i>Er is iets flink fout gegaan...</i><br>Het schip is tegen een ijsberg gevaren. Neem a.u.b contact op"; ViewBag.showHome = true; } return(View()); }
public IActionResult Status(int statusCode) { string statusPhrase = ReasonPhrases.GetReasonPhrase(statusCode); return(View(model: new StatusViewModel { statusCode = statusCode, statusPhrase = statusPhrase })); }
public IActionResult Get(int statusCode) { return(View("Status", new StatusViewModel { StatusCode = statusCode, StatusDescription = ReasonPhrases.GetReasonPhrase(statusCode) })); }
public IActionResult StatusCodePage(int id) { return(this.View(new StatusCodePageViewModel { StatusCode = id, StatusText = ReasonPhrases.GetReasonPhrase(id), })); }
public void OnGet(int?code) { Code = code; if (code.HasValue) { CodeName = ReasonPhrases.GetReasonPhrase(code.Value); } }
public async Task Invoke(HttpContext context) { try { await _next.Invoke(context); if (!SuccessCode.Contains(context.Response.StatusCode)) { int statusCode2 = context.Response.StatusCode; string reasonPhrase = ReasonPhrases.GetReasonPhrase(statusCode2); string msg = string.Format("Status Code: {0}, {1}; {2}{3}", new object[4] { statusCode2, reasonPhrase, context.Request.Path, context.Request.QueryString }); if (context.IsAjaxRequest()) { context.Response.ContentType = "application/json;charset=utf-8"; MyResult <object> response2 = new MyResult <object>(statusCode2, msg, (Exception)null); await context.Response.WriteAsync(response2.GetJson()); } } } catch (Exception exception) { int statusCode = SuccessCode.Contains(context.Response.StatusCode) ? 500 : context.Response.StatusCode; if (exception.TargetSite.DeclaringType != (Type)null) { string name = exception.TargetSite.DeclaringType.Name; if (name.Contains("ChallengeAsync")) { statusCode = 401; } else if (name.Contains("ForbidAsync")) { statusCode = 403; } } LogUtil <ErrorHandlerMiddleware> .Error($"[ErrorHandler中间件:]{exception}"); Exception ex = exception; StringBuilder message = new StringBuilder(); while (ex != null) { message.AppendLine(ex.Message); ex = ex.InnerException; } if (context.IsAjaxRequest() && !context.Response.HasStarted) { context.Response.ContentType = "application/json;charset=utf-8"; MyResult <object> response = new MyResult <object>(statusCode, message.ToString(), (Exception)null); await context.Response.WriteAsync(response.GetJson()); } } }
private IStatsDClient WithScope(HttpContext context) { var(controllerName, actionName) = context.GetControllerAndAction(); var reasonPhrase = ReasonPhrases.GetReasonPhrase(context.Response?.StatusCode ?? 0); return(statsDClient .WithScope(controllerName ?? "UnknownController") .WithScope(actionName ?? "UnknownAction") .WithScope(reasonPhrase == string.Empty ? "Unknown" : reasonPhrase)); }
public static ActionResult Result(int statusCode, string message = null) { return(new ContentResult { StatusCode = statusCode, Content = $"Status Code: {statusCode}; {ReasonPhrases.GetReasonPhrase(statusCode)}; {message ?? string.Empty}", ContentType = "text/plain" }); }
// Returns error for a given status code public IActionResult StatusError(int code) { MessageViewModel model = new MessageViewModel() { Title = $"Error {code} - {ReasonPhrases.GetReasonPhrase(code)}", MessageTitle = $"Error {code} - {ReasonPhrases.GetReasonPhrase(code)}" }; return(View("Message", model)); }
/// <inheritdoc /> /// <summary> /// Delete a gradebook column and the associated scores. /// </summary> protected override async Task <ActionResult> OnDeleteLineItemAsync(DeleteLineItemRequest 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.Any(c => c.Id == lineItemId)) { var gradebookColumn = await _context.GetGradebookColumnAsync(lineItemId); _context.GradebookColumns.Remove(gradebookColumn); await _context.SaveChangesAsync(); return(NoContent()); } return(NotFound(new ProblemDetails { Title = ReasonPhrases.GetReasonPhrase(StatusCodes.Status404NotFound), Detail = "Gradebook column not found" })); }
public async void GetNonExistingExample_ShouldReturnNotFound() { //Arrange var url = $"{BasePath}/8"; //Act var response = await GetAsync(url, false); //Assert Assert.Equal(ReasonPhrases.GetReasonPhrase(StatusCodes.Status404NotFound), response.ReasonPhrase); }
private static string RetornaMensagemErro(int statusCode) { return(statusCode switch { 400 => "O pedido não pode ser cumprido devido à erro de sintaxe.", 401 => "A chamada precisa ser efetuada por um usuario autenticado.", 403 => "O usuário esta autenticado, mas o não possui permissão para executar essa ação.", 404 => "A página solicitada não pôde ser encontrada, mas pode estar disponível novamente no futuro.", 405 => "Foi feita uma solicitação de uma página usando um método de solicitação não suportado por essa página.", _ => ReasonPhrases.GetReasonPhrase(statusCode) });
static ProblemDetailsFactory() { for (var i = 400; i < 600; i++) { ClientErrorMapping.Add(i, new ClientErrorData { Link = string.Format(STATUS_CODE_TYPE_URI, i), Title = ReasonPhrases.GetReasonPhrase(i) }); } }