// IMyScopedService is injected into Invoke public async Task InvokeAsync(HttpContext httpContext) { string method = httpContext.Request.Method.ToLower(); string path = httpContext.Request.Path; int statusCode = httpContext.Response.StatusCode; if (("post" == method) && (path == EventManagerConstants.EventReceptionPath)) { string responseBody = await new StreamReader(httpContext.Request.Body).ReadToEndAsync(); JObject json = JObject.Parse(responseBody); Event e = new Event() { Name = (string)json["Name"], Timestamp = (DateTime)json["Timestamp"], Payload = json["Payload"].ToString(Formatting.None), ExtraParams = json["ExtraParams"].ToObject <JObject>(), ContextHeaders = httpContext.Request.Headers.ToDictionary(a => a.Key, a => (IEnumerable <string>)a.Value) }; HttpResponseMessage httpResponseMessage = EventDispatcher.Dispatch(e); // if the response message is `null` then it means the event had no synchronous callbacks and that all // async callbacks have been queued for execution, see we can return 200 status if (httpResponseMessage == null) { httpContext.Response.StatusCode = (int)HttpStatusCode.OK; } else { httpContext.Response.StatusCode = (int)httpResponseMessage.StatusCode; string contents = ""; if (httpResponseMessage.Content != null) { contents = httpResponseMessage.Content.ReadAsStringAsync().Result; // add content headers foreach (KeyValuePair <string, IEnumerable <string> > item in httpResponseMessage.Content?.Headers.AsEnumerable()) { httpContext.Response.Headers.Add(item.Key, new StringValues(item.Value.ToArray())); } } foreach (KeyValuePair <string, IEnumerable <string> > item in httpResponseMessage.Headers.AsEnumerable()) { httpContext.Response.Headers.Add(item.Key, new StringValues(item.Value.ToArray())); } // we send the contents response of the EventDispatcher.Dispatch we just called await HttpResponseWritingExtensions.WriteAsync(httpContext.Response, contents); } } else { // Call the next delegate/middleware in the pipeline await _next(httpContext); } }
private static void RequestHandler(IApplicationBuilder app, QuickApplication quickApp, bool detailedExceptions) { app.Run(async handler => { var segments = handler.Request.Path.Value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); var serviceName = segments[1]; var methodName = segments[2]; string bodyText = null; using (var stream = handler.Request.Body) { using (var reader = new StreamReader(stream)) { if (!reader.EndOfStream) { bodyText = reader.ReadToEnd(); } } } var arguments = bodyText == null ? null : JObject.Parse(bodyText); //quickApp.CallServiceMethod(serviceName, methodName, arguments); CallContext callContext; try { callContext = await quickApp.CallServiceMethod(serviceName, methodName, arguments); } catch (Exception ex) { var resultError = new ExpandoObject() as dynamic; resultError.Error = ex.GetType().Name; resultError.Message = ex.Message; if (detailedExceptions) { resultError.Exception = ex; } handler.Response.StatusCode = 500; await HttpResponseWritingExtensions.WriteAsync(handler.Response, JsonConvert.SerializeObject(resultError)); return; } if (!callContext.IsVoidMethod) { handler.Response.ContentType = "application/json; charset=utf-8"; await HttpResponseWritingExtensions.WriteAsync(handler.Response, JsonConvert.SerializeObject(callContext.Result)); } else { handler.Response.StatusCode = 204; } }); }
/// <summary> /// Runs the middleware. /// </summary> /// <param name="context">The context.</param> /// <returns>A task representing the asynchronous operation.</returns> public override async Task InvokeAsync(HttpContext context) { #pragma warning disable IDE0042 // Deconstruct variable declaration var validationResult = await this.ValidateAsync(context); #pragma warning restore IDE0042 // Deconstruct variable declaration if (validationResult.Success) { if (this.Next != null) { await this.Next.InvokeAsync(context); } } else { dynamic response = new { correlationId = context.TraceIdentifier, error = new { code = this.ErrorCode, message = validationResult.Error, }, }; context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.ContentType = ContentTypes.ApplicationJson; await HttpResponseWritingExtensions.WriteAsync(context.Response, JsonConvert.SerializeObject(response)); } }
private async Task SendToSkill(HttpResponse response, BotFrameworkSkill targetSkill, Activity activity, CancellationToken cancellationToken = default) { if (activity.Type == ActivityTypes.Invoke) { var invokeResponse = await PostActivityToSkill <JObject>(targetSkill, activity, cancellationToken); if (invokeResponse != null) { response.ContentType = "text/html"; response.StatusCode = (int)HttpStatusCode.OK; string text = $"<html><body>{System.Web.HttpUtility.HtmlEncode(invokeResponse.ToString())}</body></html>"; await HttpResponseWritingExtensions.WriteAsync(response, text); } } else { var expectedReplies = await PostActivityToSkill <ExpectedReplies>(targetSkill, activity, cancellationToken); if (expectedReplies != null && activity.DeliveryMode == DeliveryModes.ExpectReplies) { string responseText = string.Empty; foreach (var a in expectedReplies.Activities) { responseText += $"<p>ExpectedReplies: {a.Text}</p>"; } response.ContentType = "text/html"; response.StatusCode = (int)HttpStatusCode.OK; string text = $"<html><body>{responseText}</body></html>"; await HttpResponseWritingExtensions.WriteAsync(response, text); } } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Use(async(context, next) => { var token = context.Request.Headers["token"].ToString(); var customerid = context.Request.Headers["customer_id"].ToString(); ITokenService service = new TokenService(); if (!service.ValidateToken(customerid, token)) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; await HttpResponseWritingExtensions.WriteAsync(context.Response, "UnAuthorized Access Found..!"); } else { await next(); } }); app.UseMvc(); }
private async Task HandleCommand(HttpContext context, ICqrsOptions options) { var path = options.GetCommandPath(context.Request.Path.Value); if (!_commandTypes.Value.ContainsKey(path)) { throw new CommandNotFoundException($"Command '{path}' not found"); } dynamic result = null; var info = _commandTypes.Value[path]; var exposeAttribute = info.CommandType.GetCustomAttribute <ExposeAttribute>(); var formatter = _registry.GetFormatter(exposeAttribute.Formatter); var deserializeMethod = _deserializeMethods.GetOrAdd(info.CommandType, (t) => { var mi = CreateDeserializeLambdaMethodInfo.MakeGenericMethod(t); return(mi.Invoke(null, null)); }); dynamic command = await deserializeMethod(formatter, context.Request); dynamic handler = _container.GetInstance(info.CommandHandlerType); context.Items[ContextKey] = new CqrsContext(context.Request.Path.Value, path, CqrsType.Command, info.CommandHandlerType); if (info.IsGeneric) { if (info.IsAsync) { result = await handler.HandleAsync(command, context.RequestAborted); } else { result = handler.Handle(command); } } else { if (info.IsAsync) { await handler.HandleAsync(command, context.RequestAborted); } else { handler.Handle(command); } } CloseSession(); var json = result is string?result : await formatter.SerializeAsync(result, context.Request); context.Response.ContentType = formatter.ContentType; context.Response.StatusCode = (int)HttpStatusCode.OK; await HttpResponseWritingExtensions.WriteAsync(context.Response, json, context.RequestAborted); }
private async Task HandleCommand(HttpContext context, ICqrsOptions options) { var path = options.GetCommandPath(context.Request.Path.Value); if (!_commandTypes.ContainsKey(path)) { throw new CommandNotFoundException($"Command '{path}' not found"); } dynamic result = null; var info = _commandTypes[path]; var commandData = await new StreamReader(context.Request.Body).ReadToEndAsync(); dynamic command = DeserializeCommand(commandData, info.CommandType); dynamic handler = _container.GetInstance(info.CommandHandlerType); context.Items[ContextKey] = new CqrsContext(context.Request.Path.Value, path, CqrsType.Command, info.CommandHandlerType); if (info.IsGeneric) { if (info.IsAsync) { result = await handler.HandleAsync(command, context.RequestAborted); } else { result = handler.Handle(command); } } else { if (info.IsAsync) { await handler.HandleAsync(command, context.RequestAborted); } else { handler.Handle(command); } } CloseSession(); var json = result is string?result : JsonConvert.SerializeObject(result, _jsonSerializerSettings); context.Response.ContentType = ContentType; context.Response.StatusCode = (int)HttpStatusCode.OK; await HttpResponseWritingExtensions.WriteAsync(context.Response, json, context.RequestAborted); }
public override async Task InvokeAsync(HttpContext context) { try { await HttpResponseWritingExtensions.WriteAsync(context.Response, "\n Request stage - Exception Handling middleware!"); await this.Next.InvokeAsync(context); await HttpResponseWritingExtensions.WriteAsync(context.Response, "\n Response stage - Exception Handling middleware!"); } catch (Exception ex) { await Task.CompletedTask; } }
public async Task Invoke(HttpContext context) { string _authToken = _authTokens.BearerToken; string reqAuthToken = context.Request.Headers.FirstOrDefault(header => header.Key == "Authorization").Value.FirstOrDefault(); if (IsAuthorized(_authToken, reqAuthToken, context)) { await _next.Invoke(context); return; } context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; await HttpResponseWritingExtensions.WriteAsync(context.Response, "Invalid Authorization Token"); }
public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { var response = context.HttpContext.Response; var buffer = new StringBuilder(); if (context.Object is IEnumerable <CompanyDto> lsCompanyDto) { foreach (var companyDto in lsCompanyDto) { FormatCsv(buffer, companyDto); } } if (context.Object is CompanyDto CompanyDto) { FormatCsv(buffer, CompanyDto); } await HttpResponseWritingExtensions.WriteAsync(response, buffer.ToString()); }
public async void OnException(ExceptionContext context) { context = context ?? throw new ArgumentNullException(nameof(context)); if (context.Exception is KeyNotFoundException) { var response = new ResponseErrorModel(404, context.Exception.Message); var responseJson = JsonConvert.SerializeObject(response); var responseBytes = Encoding.UTF8.GetBytes(responseJson); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound; context.HttpContext.Response.ContentType = "application/json"; context.HttpContext.Response.ContentLength = responseBytes.Length; await HttpResponseWritingExtensions.WriteAsync(context.HttpContext.Response, responseJson); context.ExceptionHandled = true; return; } }
public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { using (var writer = new StringWriter()) { using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) { if (context.Object is IEnumerable <object> ) { csv.WriteRecords((IEnumerable <object>)context.Object); } else { var ls = new [] { context.Object }; csv.WriteRecords((IEnumerable <object>)ls); } } await HttpResponseWritingExtensions.WriteAsync(context.HttpContext.Response, writer.ToString()); } }
/// <summary> /// Runs the middleware. /// </summary> /// <param name="context">The context.</param> /// <returns>A task representing the asynchronous operation.</returns> public override async Task InvokeAsync(HttpContext context) { if (this.Next == null) { throw new MiddlewarePipelineException($"{this.GetType().FullName} must have a Next middleware"); } try { await this.Next.InvokeAsync(context); } catch (Exception e) { if (this.LogExceptionAsync != null) { await this.LogExceptionAsync(e); } if (this.ExceptionHandler == null) { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = ContentTypes.ApplicationJson; dynamic content = new { error = new { code = ErrorCodes.InternalServerError, message = "An internal server error occurred", }, correlationId = context.TraceIdentifier, }; await HttpResponseWritingExtensions.WriteAsync(context.Response, JsonConvert.SerializeObject(content)); } else { var result = await this.ExceptionHandler(e, context); await context.ProcessActionResultAsync(result); } } }
private async Task RespondWithIndexHtml(HttpResponse response) { response.StatusCode = 200; response.ContentType = "text/html"; List <string> namelist = new List <string>(); foreach (string str in this.GetType().Assembly.GetManifestResourceNames()) { namelist.Add(str); } Stream stream = this.GetType().Assembly.GetManifestResourceStream("Limited.DashBoard.index.html"); StringBuilder stringBuilder = new StringBuilder(new StreamReader(stream).ReadToEnd()); foreach (KeyValuePair <string, string> indexParameter in GetIndexParameters()) { stringBuilder.Replace(indexParameter.Key, indexParameter.Value); } await HttpResponseWritingExtensions.WriteAsync(response, stringBuilder.ToString(), Encoding.UTF8, default(CancellationToken)); }
private async Task HandleQuery(HttpContext context, ICqrsOptions options) { var path = options.GetQueryPath(context.Request.Path.Value); if (!_queryTypes.ContainsKey(path)) { throw new QueryNotFoundException($"Query '{path}' not found"); } // GET operations get their data through the query string, while POST operations expect a JSON // object being put in the body. var queryData = context.Request.Method == HttpMethod.Get.Method ? SerializationHelpers.ConvertQueryStringToJson(context.Request.QueryString.Value) : await new StreamReader(context.Request.Body).ReadToEndAsync(); var info = _queryTypes[path]; var query = DeserializeQuery(queryData, info.QueryType); dynamic handler = _container.GetInstance(info.QueryHandlerType); context.Items[ContextKey] = new CqrsContext(context.Request.Path.Value, path, CqrsType.Command, info.QueryHandlerType); dynamic result; if (info.IsAsync) { result = await handler.HandleAsync(query, context.RequestAborted); } else { result = handler.Handle(query); } var json = result is string?result : JsonConvert.SerializeObject(result, _jsonSerializerSettings); context.Response.ContentType = ContentType; context.Response.StatusCode = (int)HttpStatusCode.OK; await HttpResponseWritingExtensions.WriteAsync(context.Response, json, context.RequestAborted); }
public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILoggerManager logger) { app.UseExceptionHandler(appError => { appError.Run(async context => { context.Response.StatusCode = StatusCodes.Status500InternalServerError;// (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json"; var contextFeature = context.Features.Get <IExceptionHandlerFeature>(); if (contextFeature != null) { logger.LogError($"Something went wrong: {contextFeature.Error}"); var errDetail = new ErrorDetails() { StatusCode = context.Response.StatusCode, Message = "Internal Server Error." }; // await context.Response.Body.WriteAsync(errDetail.ToString()); await HttpResponseWritingExtensions.WriteAsync(context.Response, errDetail.ToString()); } }); }); }
private async Task RedirectToService(HttpContext context, string hubName, IList <IAuthorizeData> authorizationData) { if (!await AuthorizeHelper.AuthorizeAsync(context, authorizationData)) { return; } NegotiationResponse negotiateResponse = null; try { negotiateResponse = _negotiateHandler.Process(context, hubName); } catch (AzureSignalRAccessTokenTooLongException ex) { Log.NegotiateFailed(_logger, ex.Message); context.Response.StatusCode = 413; await HttpResponseWritingExtensions.WriteAsync(context.Response, ex.Message); return; } var writer = new MemoryBufferWriter(); try { context.Response.ContentType = "application/json"; NegotiateProtocol.WriteResponse(negotiateResponse, writer); // Write it out to the response with the right content length context.Response.ContentLength = writer.Length; await writer.CopyToAsync(context.Response.Body); } finally { writer.Reset(); } }
private async Task <IActionResult> ExecuteFunctions(HttpContext context) { await HttpResponseWritingExtensions.WriteAsync(context.Response, "\n Hi from serverless middleware functions !"); throw new Exception("Exception thrown from functions!"); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); string connectionString = _configuration.GetConnectionString("DefaultConnection"); Debug.Assert(!String.IsNullOrEmpty(connectionString), "connection string is null or empty"); if (DbTypes.IsInMemory() || _environment.IsTest()) { services.AddDbContext <BooksDbContext>(options => { options.UseInMemoryDatabase("books"); }); } else if (DbTypes.IsMySql()) { services.AddDbContext <BooksDbContext>(options => { options.UseMySql(connectionString); }); } else if (DbTypes.IsSqlite()) { services.AddDbContext <BooksDbContext>(options => { options.UseSqlite(connectionString); }); } else { services.AddDbContext <BooksDbContext>(options => { options.UseSqlServer(connectionString); }); } services.AddIdentity <IdentityUser <Guid>, IdentityRole <Guid> >(config => { config.SignIn.RequireConfirmedEmail = true; }) .AddEntityFrameworkStores <BooksDbContext>() .AddUserManager <UserManager <IdentityUser <Guid> > >() .AddRoleManager <RoleManager <IdentityRole <Guid> > >(); services.AddTransient <TokenService>(); services.AddCors(o => o.AddPolicy("AllowAll", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); })); services.AddControllers() .AddNewtonsoftJson(options => { options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }) .AddMvcOptions(options => { options.EnableEndpointRouting = false; options.RespectBrowserAcceptHeader = true; }); services.AddLogging(); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { var jwtSection = _configuration.GetSection("Jwt"); Debug.Assert(jwtSection.Exists(), "Jwt section missing in appsettings"); string secret = _configuration.GetSection("Jwt")["Secret"]; Debug.Assert(!String.IsNullOrEmpty(secret), "Jwt secret missing in appsettings"); string audience = _configuration.GetSection("Jwt")["Audience"]; Debug.Assert(!String.IsNullOrEmpty(audience), "Jwt audience missing in appsettings"); string authority = _configuration.GetSection("Jwt")["Authority"]; var key = Encoding.UTF8.GetBytes(secret); Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = _environment.IsTestOrDevelopment(); x.Events = new JwtBearerEvents() { OnAuthenticationFailed = context => { context.Response.StatusCode = 401; context.Response.ContentType = "application/json; charset=utf-8"; var message = _environment.IsTestOrDevelopment() ? context.Exception.ToString() : "An error occurred processing your authentication."; var result = Newtonsoft.Json.JsonConvert.SerializeObject(new { message }); return(HttpResponseWritingExtensions.WriteAsync(context.Response, result)); } }; x.RequireHttpsMetadata = !_environment.IsTestOrDevelopment(); x.SaveToken = true; x.Audience = audience; if (String.IsNullOrEmpty(authority)) { // use local validation x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; } else { // use sso validation x.Authority = authority; } }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "Books API", Description = "API for Books", TermsOfService = new Uri("http://tempuri.org/terms"), Contact = new OpenApiContact() { Name = "Mykeels.", Email = "*****@*****.**", Url = new Uri("https://twitter.com/mykeels") } }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); }
private async Task WriteResultInResponse(HttpContext httpContext, ApiMockerResult result) { httpContext.Response.StatusCode = result.StatusCode; httpContext.Response.ContentType = result.ContentType; await HttpResponseWritingExtensions.WriteAsync(httpContext.Response, result.Content); }