/// <summary></summary> public override async Task ExecuteResultAsync(ActionContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (!AllowGet && string.Equals(context.HttpContext.Request.Method, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request."); } var response = context.HttpContext.Response; response.ContentType = ContentType; if (StatusCode != null) { response.StatusCode = StatusCode.Value; } var jsonResult = new JsonResult(Data) { StatusCode = StatusCode, ContentType = ContentType }; await jsonResult.ExecuteResultAsync(context); }
public override Task ExecuteResultAsync(ActionContext context) { context.HttpContext.Response.StatusCode = StatusCode; var json = new JsonResult(this); return(json.ExecuteResultAsync(context)); }
public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { context.Response.Clear(); context.Response.Headers.Clear(); context.Response.StatusCode = 500; if (_hostingEnvironment.IsDevelopment()) { JsonResult result = new JsonResult(ex); RouteData routeData = context.GetRouteData(); ActionDescriptor actionDescriptor = new ActionDescriptor(); ActionContext actionContext = new ActionContext(context, routeData ?? new RouteData(), actionDescriptor); await result.ExecuteResultAsync(actionContext); return; } _logger.LogError("An unhandled exception has occurred: " + ex.Message, ex); if (context.Response.HasStarted) { _logger.LogWarning("The response has already started, the error handler will not be executed."); } } }
public override async Task ExecuteResultAsync(ActionContext context) { ILogger <EgressStreamResult> logger = context.HttpContext.RequestServices .GetRequiredService <ILoggerFactory>() .CreateLogger <EgressStreamResult>(); using var _ = logger.BeginScope(_scope); await context.InvokeAsync(async (token) => { IEgressService egressService = context.HttpContext.RequestServices .GetRequiredService <IEgressService>(); EgressResult egressResult = await _egress(egressService, token); logger.LogInformation("Egressed to {0}", egressResult.Value); // The remaining code is creating a JSON object with a single property and scalar value // that indiates where the stream data was egressed. Because the name of the artifact is // automatically generated by the REST API and the caller of the endpoint might not know // the specific configuration information for the egress provider, this value allows the // caller to more easily find the artifact after egress has completed. IDictionary <string, string> data = new Dictionary <string, string>(StringComparer.Ordinal); data.Add(egressResult.Name, egressResult.Value); ActionResult jsonResult = new JsonResult(data); await jsonResult.ExecuteResultAsync(context); }, logger); }
public async Task ExecuteResultAsync(ActionContext context) { if (context.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest") { var jsonResult = new JsonResult(_feedback); if (_feedback.Tipo == TipoFeedback.Erro || _feedback.Tipo == TipoFeedback.Atencao) { jsonResult.StatusCode = (int)HttpStatusCode.BadRequest; } await jsonResult.ExecuteResultAsync(context); } else { var viewResult = new ViewResult { ViewName = "_Feedback", ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), context.ModelState) { Model = _feedback } }; await viewResult.ExecuteResultAsync(context); } }
public async Task ExecuteResultAsync(ActionContext context) { var jsonResult = new JsonResult(this); jsonResult.StatusCode = StatusCodes.Status422UnprocessableEntity; await jsonResult.ExecuteResultAsync(context); }
public async Task ExecuteResultAsync(ActionContext context) { var json = new JsonResult(this) { StatusCode = 404 }; await json.ExecuteResultAsync(context); }
/// <inheritdoc /> public override async Task ExecuteResultAsync(ActionContext context) { var jsonResult = new JsonResult(this) { StatusCode = (int)_statusCode }; await jsonResult.ExecuteResultAsync(context); }
protected async Task Execute(ActionContext context, int?statusCode) { var jsonResult = new JsonResult(_response) { StatusCode = statusCode }; await jsonResult.ExecuteResultAsync(context); }
public virtual async Task ExecuteAsync(ActionContext context, ApiResult result) { var jsonResult = new JsonResult(result.Value) { StatusCode = result.StatusCode }; await jsonResult.ExecuteResultAsync(context); }
public async Task ExecuteResultAsync(ActionContext context) { var result = new JsonResult(Value) { StatusCode = (int)(Value.Failure?.GetStatusCode() ?? HttpStatusCode.OK) }; await result.ExecuteResultAsync(context); }
public Task ExecuteResultAsync(ActionContext context) { var jsonResult = new JsonResult(_response); jsonResult.StatusCode = StatusCodes.Status400BadRequest; return(jsonResult.ExecuteResultAsync(context)); }
private async Task WriteJsonResponse(HttpContext context, object contract) { var routeData = context.GetRouteData() ?? new RouteData(); var actionDescriptor = new ActionDescriptor(); var actionContext = new ActionContext(context, routeData, actionDescriptor); var response = new JsonResult(contract); await response.ExecuteResultAsync(actionContext); }
/// <summary> /// Handle exception. /// </summary> /// <param name="context">The cu<see cref="Filters.ExceptionContext"/>.</param> /// <returns>The task to handle exception.</returns> public override async Task OnExceptionAsync(Filters.ExceptionContext context) { Guard.ArgumentNotNull(context, nameof(context)); context.ExceptionHandled = true; _options = context.HttpContext.RequestServices.GetRequiredService <IOptions <HandleExceptionFilterOptions> >().Value; if (context.Exception == null) { return; } ExceptionManager manager = context.HttpContext.RequestServices.GetRequiredService <ExceptionManager>(); string exceptionPolicy = this.GetExceptionPolicy(context); try { if (!string.IsNullOrEmpty(exceptionPolicy)) { await manager.HandleExceptionAsync(context.Exception, exceptionPolicy); } else { manager.HandleExceptionAsync(context.Exception).Wait(); } } catch (Exception ex) { ex = (ex as AggregateException)?.InnerException ?? ex; var exceptionInfo = new ExceptionInfo(ex, _options.IncludeInnerException); if (this.TryGetHandlerAction(context, out ActionDescriptor handlerAction)) { context.HttpContext.SetExceptionInfo(exceptionInfo); ActionContext actionContext = new ActionContext(context.HttpContext, context.RouteData, handlerAction); IActionInvoker actionInvoker = context.HttpContext.RequestServices.GetRequiredService <IActionInvokerFactory>().CreateInvoker(actionContext); await actionInvoker.InvokeAsync(); return; } if (context.HttpContext.IsAjaxRequest()) { JsonResult json = new JsonResult(exceptionInfo, _options.JsonSerializerSettings); await json.ExecuteResultAsync(new ActionContext(context)); return; } var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), context.ModelState) { Model = exceptionInfo }; ViewResult view = new ViewResult { ViewData = viewData }; await view.ExecuteResultAsync(context); } }
public async Task ExecuteResultAsync(ActionContext context) { var jsonResult = new JsonResult(this) { ContentType = "application/json", StatusCode = IsSuccess ? StatusCodes.Status200OK : StatusCodes.Status400BadRequest, Value = this }; await jsonResult.ExecuteResultAsync(context); }
public async Task ExecuteResultAsync(ActionContext context) { var jsonResult = new JsonResult(_saida) { StatusCode = !_saida.Sucesso ? (int)HttpStatusCode.BadRequest : (int)HttpStatusCode.OK }; await jsonResult.ExecuteResultAsync(context); }
public async Task ExecuteResultAsync(ActionContext context) { var notificationService = context.HttpContext.RequestServices.GetService <INotificationService>(); Notification[] notifications = notificationService.GetNotifications(); if (result.Notifications != null && result.Notifications.Length > 0) { notifications = result.Notifications.Concat(notifications).ToArray(); } result.Notifications = notifications; await jsonResult.ExecuteResultAsync(context); }
public async Task ExecuteResultAsync(ActionContext context) { var jsonResult = new JsonResult(new { _draw, recordsTotal = _totalRegistros, recordsFiltered = _totalRegistros, data = _itens }); await jsonResult.ExecuteResultAsync(context); }
public async Task ExecuteResultAsync(ActionContext context) { var apiMessage = new ApiResponseMessage <object> { Code = _code, Message = _message, Info = _info }; var json = new JsonResult(apiMessage); context.HttpContext.Response.StatusCode = (int)_code; await json.ExecuteResultAsync(context); }
private async Task InvokeJson(HttpContext context, Exception ex) { context.Response.Clear(); context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; var messageResult = new MyExceptionResult() { Message = ex.Message, Data = ex, Success = false }; var result = new JsonResult(messageResult); var routeData = context.GetRouteData(); var actionDescriptor = new ActionDescriptor(); var actionContext = new ActionContext(context, routeData, actionDescriptor); await result.ExecuteResultAsync(actionContext); }
public override Task ForbidAsync(HttpContext context, string scheme, AuthenticationProperties properties) { if (context.Items.ContainsKey(AuthorizationPolicyEvaluator.contextKey)) { var options = context.Items[AuthorizationPolicyEvaluator.contextKey] as ForbiddenException; var routeData = context.GetRouteData(); var actionDescriptor = new ActionDescriptor(); var actionContext = new ActionContext(context, routeData, actionDescriptor); var actionResult = new JsonResult(options) { StatusCode = (int)HttpStatusCode.Forbidden }; return(actionResult.ExecuteResultAsync(actionContext)); } return(base.ForbidAsync(context, scheme, properties)); }
public Task ExecuteResultAsync(ActionContext actionContext) { actionContext.HttpContext.Response.StatusCode = (int)StatusCode; // Requested headers Headers.Values.OfType <IHttpHeaderProperty>() .Run(x => actionContext.HttpContext.Response.Headers[x.Key] = new StringValues(x.FormatValueForHttp())); // Standard headers actionContext.HttpContext.Response.Headers[CvHeader.HeaderKey] = new CvHeader(Context.Cv).FormatValueForHttp(); DebugEventContractV1 debugObject = ProcessDebug(actionContext); if (Content != null) { if (debugObject == null) { var objectResult = new ObjectResult(Content); return(objectResult.ExecuteResultAsync(actionContext)); } // Append debug data to response if (Content != null && debugObject != null) { // Embedded debug data JObject contentObj = JObject.FromObject(Content); JObject debugObj = JObject.FromObject(debugObject); contentObj.Add("debug", debugObj); // Indicate that the debug data is present var header = new TestDumpHeader(TestDumpHeader.Commands.Reponse); actionContext.HttpContext.Response.Headers[header.Key] = header.FormatValueForHttp(); var jsonResult = new JsonResult(contentObj); return(jsonResult.ExecuteResultAsync(actionContext)); } } if (debugObject != null) { var objectResult = new ObjectResult(debugObject); return(objectResult.ExecuteResultAsync(actionContext)); } return(Task.FromResult(0)); }
private Task HandleExceptionAsync(HttpContext context, Exception exception) { context.Response.ContentType = "application/json"; var exceptionResponse = new ResponseWrapper() { IsSuccess = false, Message = exception.Message, Data = null }; JsonResult result = new JsonResult(exceptionResponse); RouteData routeData = context.GetRouteData(); ActionDescriptor actionDescriptor = new ActionDescriptor(); ActionContext actionContext = new ActionContext(context, routeData, actionDescriptor); return(result.ExecuteResultAsync(actionContext)); }
public async override Task ExecuteResultAsync(ActionContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var errorVm = new ErrorVm() { Code = ErrorCode.ValidationFailed, ValidationDictionnay = ToValidation(modelState) }; var jsonResult = new JsonResult(errorVm); jsonResult.StatusCode = StatusCodes.Status400BadRequest; await jsonResult.ExecuteResultAsync(context); }
public async Task ExecuteResultAsync_ThrowsIfExecutorIsNotAvailableInServices() { // Arrange var jsonResult = new JsonResult("Hello"); var message = "'JsonResult.ExecuteResultAsync' requires a reference to 'Microsoft.AspNetCore.Mvc.NewtonsoftJson'. " + "Configure your application by adding a reference to the 'Microsoft.AspNetCore.Mvc.NewtonsoftJson' package and calling 'IMvcBuilder.AddNewtonsoftJson' " + "inside the call to 'ConfigureServices(...)' in the application startup code."; var actionContext = new ActionContext { HttpContext = new DefaultHttpContext { RequestServices = Mock.Of <IServiceProvider>() } }; // Act & Assert var ex = await Assert.ThrowsAsync <InvalidOperationException>(() => jsonResult.ExecuteResultAsync(actionContext)); Assert.Equal(message, ex.Message); }
public async Task Invoke(HttpContext httpContext) { try { await _next.Invoke(httpContext); } catch (Exception ex) { var result = new JsonResult(new { ex.Message }) { StatusCode = (int?)HttpStatusCode.BadRequest }; var routeData = httpContext.GetRouteData(); var actionDescriptor = new ActionDescriptor(); var actionContext = new ActionContext(httpContext, routeData, actionDescriptor); await result.ExecuteResultAsync(actionContext); } }
public async Task ExecuteAsync_WritesJsonContent() { // Arrange var value = new { foo = "abcd" }; var expected = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value)); var context = GetActionContext(); var result = new JsonResult(value); // Act await result.ExecuteResultAsync(context); // Assert var written = GetWrittenBytes(context.HttpContext); Assert.Equal(expected, written); Assert.Equal("application/json; charset=utf-8", context.HttpContext.Response.ContentType); }
public Task ExecuteResultAsync(ActionContext context) { if (!operationResult.Ok) { var jsonResult = new JsonResult(operationResult.ErrorMessage, new JsonSerializerOptions()//new JsonSerializerSettings() { //ContractResolver = new CamelCasePropertyNamesContractResolver(), }); switch (operationResult.ErrorType) { case ErrorType.InvalidForm: { jsonResult.StatusCode = 400; break; } case ErrorType.InvalidInnerState: { jsonResult.StatusCode = 406; break; } case ErrorType.NotFound: { jsonResult.StatusCode = 404; break; } default: throw new NotImplementedException(); //return jsonResult.ExecuteResultAsync(context); } return(jsonResult.ExecuteResultAsync(context)); } return(new JsonResult(operationResult).ExecuteResultAsync(context)); }
public override Task ExecuteResultAsync(ActionContext context) { var json = new JsonResult(this, JsonSerializerSettingsProvider.SerializerSettings()); return(json.ExecuteResultAsync(context)); }
public static IEndpointConventionBuilder UseFilteredAutoForeignKeys(this IEndpointRouteBuilder builder, string explicitTenantParam, bool forAreas, bool withAuthorization = true) { bool forExplicitTenants = !string.IsNullOrEmpty(explicitTenantParam); ContextExtensions.Init(); RequestDelegate dlg = async context => { //{{connection:regex(^[\\w_]+$)}}/{{table:regex(^[\\w_]+$)}} RouteData routeData = context.GetRouteData(); ActionDescriptor actionDescriptor = new ActionDescriptor(); ActionContext actionContext = new ActionContext(context, routeData, actionDescriptor); var ok = !withAuthorization || context.RequestServices.VerifyCurrentUser(); if (ok) { if (context.Request.RouteValues.ContainsKey("dataResolveHint")) { var baseHint = ((string)context.Request.RouteValues["dataResolveHint"])?.Split("/") .Select(n => HttpUtility.UrlDecode(n)).ToArray(); if (baseHint is { Length : 2 }) { string area = null; if (context.Request.RouteValues.ContainsKey("area")) { area = (string)context.Request.RouteValues["area"]; } var connection = RegexValidate(baseHint[0], "^[\\w_]+$") ? baseHint[0] : null; //(string) context.Request.RouteValues["connection"]; var dbContext = context.RequestServices.ContextForFkQuery(connection, area); if (dbContext != null) { var table = RegexValidate(baseHint[1], dbContext.CustomFkSettings?.CustomTableValidation ?? "^[\\w_]+$") ? baseHint[1] : null; //(string) context.Request.RouteValues["table"]; FormReader former = new FormReader(context.Request.Body); var formsDictionary = await former.ReadFormAsync(); //LogEnvironment.LogEvent(Stringify(formsDictionary), LogSeverity.Report); var newDic = TranslateForm(formsDictionary, true); JsonResult result = null; bool authorized = true; try { result = new JsonResult(dbContext.ReadForeignKey(table, postedFilter: newDic) .ToDummyDataSourceResult()); } catch (SecurityException) { authorized = false; } if (authorized) { await result.ExecuteResultAsync(actionContext); return; } UnauthorizedResult ill = new UnauthorizedResult(); await ill.ExecuteResultAsync(actionContext); return; } } }