private static async Task EverythingHandlerAsync(IOwinResponse response) { Log.Application.Debug("Everything handler started."); var lines = new List <string>(); using (var stream = new FileStream(@"Logs\Status.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var reader = new StreamReader(stream)) { var line = await reader.ReadLineAsync(); while (line != null) { lines.Add(line); line = await reader.ReadLineAsync(); } } } lines.Reverse(); using (var streamWriter = new StreamWriter(response.Body)) { foreach (var line in lines) { await streamWriter.WriteLineAsync(line); } } Log.Application.Debug("Everything handler completed."); }
private EventResponseModel ToResponse(IOwinResponse response, StreamHelper outputStream, string transactionId) { var rspHeaders = LoggerHelper.ToHeaders(response.Headers, debug); // ResponseBody string contentEncoding = ""; rspHeaders.TryGetValue("Content-Encoding", out contentEncoding); var body = LoggerHelper.GetOutputFilterStreamContents(outputStream, contentEncoding); var bodyWrapper = LoggerHelper.Serialize(body, response.ContentType); // Add Transaction Id to Response Header rspHeaders = LoggerHelper.AddTransactionId("X-Moesif-Transaction-Id", transactionId, rspHeaders); var eventRsp = new EventResponseModel() { Time = DateTime.UtcNow, Status = response.StatusCode, Headers = rspHeaders, Body = bodyWrapper.Item1, TransferEncoding = bodyWrapper.Item2 }; return(eventRsp); }
private Task ProcessMatchingExpectation(IOwinResponse response, HttpExpectation httpExpectation) { var httpResponseExpectation = httpExpectation.Response; if (httpExpectation.ResponseExpectationCallback != null) { httpResponseExpectation = httpExpectation.ResponseExpectationCallback.Invoke(); } var expectedResults = string.Empty; if (httpResponseExpectation != null) { response.StatusCode = (int)httpResponseExpectation.StatusCode; expectedResults = httpResponseExpectation.ExpectedResult; if (httpResponseExpectation.Headers != null) { foreach (var key in httpResponseExpectation.Headers.AllKeys) response.Headers.Add(key, new[] {httpResponseExpectation.Headers[key]}); } } if (response.Headers != null) response.Headers.Add("Content-Type", new[] {"application/json"}); Task.Delay(_expect.ResponseTime).Wait(); return response.WriteAsync(expectedResults); }
private Task SerializeResponse(IOwinResponse response, JRpcResponse rpcResponse) { var str = JsonConvert.SerializeObject(rpcResponse, _jsonSerializerSettings); response.ContentType = "application/json"; return(response.WriteAsync(str)); }
public override async Task Invoke(IOwinContext context) { IOwinRequest request = context.Request; IOwinResponse response = context.Response; //this doesn't work in API when user object is not strictly initialised /*string userName = (request.User != null && request.User.Identity.IsAuthenticated) ? request.User.Identity.Name : "anonymous";*/ SetRequestId(request); _log.D("=> {requestMethod} {requestUri}...", request.Method, request.Uri); var stopwatch = new Stopwatch(); stopwatch.Start(); try { await Next.Invoke(context); } catch (Exception ex) { stopwatch.Stop(); _log.D("<= {statusCode} {requestMethod} {requestUri} ({time}ms).", response.StatusCode, request.Method, request.Uri, stopwatch.ElapsedMilliseconds, ex); throw; } stopwatch.Stop(); _log.D("<= {requestMethod} {requestUri} ({time}ms).", request.Method, request.Uri, stopwatch.ElapsedMilliseconds); }
/// <summary> /// Helper method to write the contents of <paramref name="inputStream"/> to the <paramref name="response"/> body. Depending on the /// accepted encodings (<paramref name="acceptEncoding"/> argument), the result will be compressed or not. /// </summary> /// <param name="acceptEncoding">The Request's accepted encodings.</param> /// <param name="response">Response to be written.</param> /// <param name="inputStream">The input stream the will be written into the Response.</param> public static async Task WriteCompressedStream(string acceptEncoding, IOwinResponse response, MemoryStream inputStream) { IDeCompressor compressor = CheckSupportedCompression(acceptEncoding); byte[] buffer; #if !DISABLE_COMPRESSION if (compressor == null) { #endif buffer = inputStream.ToArray(); response.ContentLength = buffer.Length; await response.Body.WriteAsync(buffer, 0, buffer.Length); return; #if !DISABLE_COMPRESSION } #endif using (MemoryStream compressedStream = (MemoryStream)Compress(compressor, inputStream)) buffer = compressedStream.ToArray(); response.Headers["Content-Encoding"] = compressor.EncodingName; // If there were multiple methods supported, we need to indicate the varying header. if (acceptEncoding != compressor.EncodingName) { response.Headers["Vary"] = "Accept-Encoding"; } response.ContentLength = buffer.Length; await response.Body.WriteAsync(buffer, 0, buffer.Length); }
private static async Task GetAsHumanReadable(IOwinResponse owinResponse, MetricsConfig config) { var report = new StringReporter(); report.RunReport(config.Registry, config.HealthStatus); owinResponse.ContentType = "text/plain"; await owinResponse.WriteAsync(report.Result); }
public static void CopyTo(this WebHeaderCollection headers, string header, IOwinResponse response, params string[] defaultValues) { var values = headers.GetValues(header) ?? defaultValues; if (values == null || !values.Any()) { return; } switch (header.ToLower()) { case Constants.HeaderConstants.ContentType: response.ContentType = string.Join(", ", values); return; case Constants.HeaderConstants.ContentLenght: response.ContentLength = long.Parse(values.First()); return; case Constants.HeaderConstants.TansferEncoding: var action = response.Context.Get <Action>("server.DisableResponseBuffering"); if (action != null) { action(); } return; } response.Headers.SetValues(header, values); }
private void EnableCors(IAppBuilder appBuilder) { appBuilder.Use(async(context, next) => { var serveri = new[] { "*", "http://localhost" }; IOwinRequest req = context.Request; IOwinResponse res = context.Response; var origin = req.Headers.Get("Origin"); if (!String.IsNullOrWhiteSpace(origin) && !res.Headers.ContainsKey("Access-Control-Allow-Origin")) { res.Headers.Set("Access-Control-Allow-Origin", origin); res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Credentials", "true"); } if (req.Method == "OPTIONS") { res.StatusCode = 200; res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST", "PUT", "DELETE"); res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", "authorization", "content-type"); return; } await next(); }); }
public virtual async Task <string> GetResponseStringAsync(IOwinResponse response) { if (!response.Body.CanSeek) { throw new Exception("The body does not support seek. Ensure that the RewindResponseMiddleware is registered earlier in the pipeline"); } if (!ShouldProcess(response)) { throw new Exception("ShouldProcess predicate failed. This processor should not read this type of response"); } var responseStream = response.Body as MemoryStream; if (responseStream == null) { throw new Exception("The response.body could not be cast as MemoryStream. Ensure that the RewindResponseMiddleware is registered earlier in the pipeline"); } responseStream.Seek(0, SeekOrigin.Begin); var reader = new StreamReader(responseStream); string body = await reader.ReadToEndAsync(); return(body); }
private APIGatewayProxyResponse MarshalResponse(IOwinResponse owinResponse) { var response = new APIGatewayProxyResponse { StatusCode = owinResponse.StatusCode }; using (var reader = new StreamReader(owinResponse.Body, Encoding.UTF8)) { response.Body = reader.ReadToEnd(); } response.Headers = new Dictionary <string, string>(); foreach (var owinResponseHeader in owinResponse.Headers) { if (owinResponseHeader.Value.Length == 1) { response.Headers[owinResponseHeader.Key] = owinResponseHeader.Value[0]; } else { response.Headers[owinResponseHeader.Key] = string.Join(",", owinResponseHeader.Value); } } return(response); }
public InfinityServerSite(ProxyUri uri, IOwinRequest request, IOwinResponse response) { this.Uri = uri; this.Request = request; this.Response = response; this.RequestOption = GetSourceRequestOption(); }
public void LogResponseSync(IOwinResponse response) { var request = response.Context.Request; RequestLine = string.Format("{0} {1}", request.Method, request.Path).Trim(); StatusCode = (HttpStatusCode)response.StatusCode; var allowed = contentAllowedLog.Any(i => response.Headers["Content-Type"].AsString("").Contains(i)); if (allowed) { Body = HandleResponseMessage(response); if (Body.ValidateJSON()) { var ignores = response.Headers.FirstOrDefault(x => x.Key == "X-Ignore-Fields"); if (!ignores.IsNull() && ignores.Value?.Count() > 0) { var body = JToken.Parse(Body).RemoveFields(ignores.Value); Body = body.ToString(Formatting.None); } } } else { Body = "Body-Ignored"; } LogResponseSync(); }
private async Task SendResponseContentAsync(HttpRequestMessage request, HttpResponseMessage response, IOwinResponse owinResponse, CancellationToken cancellationToken) { Contract.Assert(response != null); Contract.Assert(response.Content != null); Exception exception; cancellationToken.ThrowIfCancellationRequested(); try { await response.Content.CopyToAsync(owinResponse.Body); return; } catch (OperationCanceledException) { // Propogate the canceled task without calling exception loggers; throw; } catch (Exception ex) { exception = ex; } // We're streaming content, so we can only call loggers, not handlers, as we've already (possibly) send the // status code and headers across the wire. Log the exception, but then just abort. ExceptionContext exceptionContext = new ExceptionContext(exception, OwinExceptionCatchBlocks.HttpMessageHandlerAdapterStreamContent, request, response); await _exceptionLogger.LogAsync(exceptionContext, cancellationToken); await AbortResponseAsync(); }
public void Setup(IOwinContext context, IWaConfig config) { this.context = context; this.request = context.Request; this.response = context.Response; this.config = config; }
public async Task LEGACY_Can_Pass_Request_Details_For_Filtering() { // given var context = new MockOwinContextBuilder().Build(); var configuration = new TelemetryConfigurationBuilder().Build(); IOwinRequest filteredRequest = null; IOwinResponse filteredResponse = null; var sut = new OperationIdContextMiddleware( new HttpRequestTrackingMiddleware( new NoopMiddleware(), configuration, (req, resp) => { filteredRequest = req; filteredResponse = resp; return(false); }), new OperationIdContextMiddlewareConfiguration()); // when await sut.Invoke(context); // then filteredRequest.ShouldBeEquivalentTo(context.Request); filteredResponse.ShouldBeEquivalentTo(context.Response); }
private static Task WriteAsync(As4Message message, IOwinResponse response) { var responseMime = As4MessageToMimeEntity.Serialize(message); response.ContentType = responseMime.ContentType.MimeType + responseMime.ContentType.Parameters; return(responseMime.WriteToAsync(response.Body, true)); }
public static void Exception(this IOwinResponse response, Exception exception, bool hideExceptionDetail) { var exceptionResponse = hideExceptionDetail ? new ExceptionResponse(exception) : new DetailedExceptionResponse(exception); response.StatusCode = (int)HttpStatusCode.InternalServerError; response.Json(exceptionResponse); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context and user manager to use a single instance per request //app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext <EdugameCloudUserManager>(() => new EdugameCloudUserManager()); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider app.UseCookieAuthentication(new CookieAuthenticationOptions()); /////app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Configure the application for OAuth based flow PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId, () => new EdugameCloudUserManager()), //AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), // TODO: config?? AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(15), AllowInsecureHttp = HttpContext.Current.IsDebuggingEnabled, }; // NOTE: on prod environment we use Access-Control-Allow- headers from the root website if (HttpContext.Current.IsDebuggingEnabled) { app.Use(async(context, next) => { IOwinRequest req = context.Request; IOwinResponse res = context.Response; // for auth2 token requests if (req.Path.StartsWithSegments(new PathString("/Token"))) { // if there is an origin header var origin = req.Headers.Get("Origin"); if (!string.IsNullOrEmpty(origin)) { // allow the cross-site request res.Headers.Set("Access-Control-Allow-Origin", origin); } // if this is pre-flight request if (req.Method == "OPTIONS") { // respond immediately with allowed request methods and headers res.StatusCode = 200; res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST"); res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", "authorization", "content-type"); // no further processing return; } } // continue executing pipeline await next(); }); } // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); }
public void Invoke_ShouldHandleAndReturn200() { //Arrange var context = _fixture.Create <IOwinContext>(); _handlerPool.Add(new ThermometerHandler(new ThermometerQuestion("/abc", "def"), req => new { result = "ghi" })); context.Stub(x => x.Request).Return(_fixture.Create <IOwinRequest>()); context.Request.Stub(x => x.Path).Return(new PathString("/abc")); //context.Request.Stub(x => x.ToThermometerQuestion()).Return(new ThermometerQuestion("/abc", "/abc")); IOwinResponse response = MockRepository.GenerateStub <IOwinResponse>(); context.Stub(x => x.Response).Return(response); context.Response.Stub(x => x.WriteAsJson(Arg <object> .Is.Anything)); response.StatusCode = 200; _nextMiddleware.Stub(x => x.Invoke(context)).Return(Task.FromResult("success")); //Act _sut.Invoke(context); //Assert context.Response.AssertWasCalled(x => x.WriteAsJson(Arg <object> .Is.Anything)); Assert.AreEqual(200, response.StatusCode); _nextMiddleware.AssertWasCalled(x => x.Invoke(context)); }
/// <summary> /// Owin middleware invoker /// </summary> public override async Task Invoke(IOwinContext context) { IOwinRequest request = context.Request; IOwinResponse response = context.Response; DateTimeOffset requestTime = DateTimeOffset.UtcNow; Stopwatch sw = new Stopwatch(); sw.Start(); string httpCorrelationId = null; string[] correlationIdValues; if (request.Headers.TryGetValue(_httpCorrelationHeaderKey, out correlationIdValues)) { httpCorrelationId = correlationIdValues.First(); } await Next.Invoke(context); sw.Stop(); string uriToLog = request.Uri.ToString(); bool didStripQueryParams = false; if (!_captureRequestParams && request.QueryString.HasValue) { uriToLog = uriToLog.Substring(0, uriToLog.Length - request.QueryString.Value.Length - 1); didStripQueryParams = true; } string verb = request.Method; Dictionary <string, string[]> requestHeaders = CaptureHeaders(_captureRequestHeaders, request.Headers); Dictionary <string, string[]> responseHeaders = CaptureHeaders(_captureResponseHeaders, response.Headers); await _httpLoggerRepository.Log(uriToLog, didStripQueryParams, verb, httpCorrelationId, requestTime, sw.ElapsedMilliseconds, requestHeaders, responseHeaders); }
//public void Configuration(IAppBuilder appBuilder) //{ // HttpConfiguration httpConfiguration = new HttpConfiguration(); // WebApiConfig.Register(httpConfiguration); // appBuilder.UseWebApi(httpConfiguration); // appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); // appBuilder.UseWebApi(httpConfiguration); //} public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); //config.Routes.IgnoreRoute("FilesRoute", "content/{*pathInfo}"); // config.Routes.IgnoreRoute("Content/{*pathInfo}"); config.EnableCors(); config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE")); app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); // RouteConfig.RegisterRoutes(RouteTable.Routes); WebApiConfig.Register(config); app.UseWebApi(config); app.Use(async(context, next) => { IOwinRequest req = context.Request; IOwinResponse res = context.Response; if (req.Path.StartsWithSegments(new PathString("/Token"))) { var origin = req.Headers.Get("Origin"); if (!string.IsNullOrEmpty(origin)) { res.Headers.Set("Access-Control-Allow-Origin", origin); } if (req.Method == "OPTIONS") { res.StatusCode = 200; res.Headers.AppendCommaSeparatedValues("Access-Control- Allow-Methods", "GET", "POST"); res.Headers.AppendCommaSeparatedValues("Access-Control- Allow-Headers", "authorization", "content-type"); return; } } await next(); }); // Database.SetInitializer(new MigrateDatabaseToLatestVersion<AuthContext, ExpenseBuddy.Migrations.Configuration>()); }
/// <summary> /// Method to be invoked on the pipeline. /// </summary> /// <param name="context">The current owin context</param> /// <returns></returns> public override Task Invoke(IOwinContext context) { IOwinRequest owinRequest = context.Request; IOwinResponse owinResponse = context.Response; if (owinRequest != null) { string[] values; if (owinRequest.Headers.TryGetValue("Content-Length", out values)) { long receivedSize; long.TryParse(values.FirstOrDefault(), out receivedSize); if (receivedSize > _limit) { string message = $"Payload limit is {_limit}"; owinResponse.OnSendingHeaders(state => { OwinResponse owinResponseState = (OwinResponse)state; owinResponseState.StatusCode = 413; owinResponseState.ReasonPhrase = message; }, owinResponse); return(context.Response.WriteAsync(message));//Short-circuit pipeline } } } return(Next.Invoke(context)); }
public void Invoke_IfRouteIsIgnored_WithConstraints_CallsNextMiddleware() { // Arrange int expectedStatusCode = 0; string pathToIgnoreRoute = "constraint/10"; using (HttpServer server = new HttpServer()) { server.Configuration.Routes.IgnoreRoute("Constraints", "constraint/{id}", constraints: new { constraint = new CustomConstraint() }); server.Configuration.MapHttpAttributeRoutes(); // See IgnoreController OwinMiddleware product = CreateProductUnderTest(null, server); IOwinRequest request = CreateStubRequest(new Uri("http://somehost/" + pathToIgnoreRoute)); Mock <IOwinResponse> mock = CreateStubResponseMock(); int statusCode = 0; mock.SetupSet(r => r.StatusCode = It.IsAny <int>()).Callback <int>((s) => statusCode = s); IOwinResponse response = mock.Object; IOwinContext context = CreateStubContext(request, response); // Act Task task = product.Invoke(context); // Assert Assert.NotNull(task); task.WaitUntilCompleted(); task.ThrowIfFaulted(); Assert.Equal(expectedStatusCode, statusCode); } }
public ExpressResponse(IOwinResponse response) { _response = response; _engines.Add(".jade", new Jade()); _engines.Add(".cshtml", new Razor()); }
private Task SendResponseMessageAsync(HttpRequestMessage request, HttpResponseMessage response, IOwinResponse owinResponse, CancellationToken cancellationToken) { owinResponse.StatusCode = (int)response.StatusCode; owinResponse.ReasonPhrase = response.ReasonPhrase; // Copy non-content headers IDictionary <string, string[]> responseHeaders = owinResponse.Headers; foreach (KeyValuePair <string, IEnumerable <string> > header in response.Headers) { responseHeaders[header.Key] = header.Value.AsArray(); } HttpContent responseContent = response.Content; if (responseContent == null) { SetHeadersForEmptyResponse(responseHeaders); return(TaskHelpers.Completed()); } else { // Copy content headers foreach (KeyValuePair <string, IEnumerable <string> > contentHeader in responseContent.Headers) { responseHeaders[contentHeader.Key] = contentHeader.Value.AsArray(); } // Copy body return(SendResponseContentAsync(request, response, owinResponse, cancellationToken)); } }
private string HandleHttpError(IOwinResponse response) { var bodyString = ReadBodyStreamAsString(response.Body); if (!bodyString.IsNullOrWhiteSpace()) { try { JObject error = JObject.Parse(bodyString); var exceptionMessage = error["ExceptionMessage"]; var stackTrace = error["StackTrace"]; if (!exceptionMessage.IsNull() && !stackTrace.IsNull()) { var message = new { message = exceptionMessage.ToString(), traces = stackTrace.ToString() }; return(message.ToJsonString()); } } catch { return(response.ReasonPhrase); } } return(response.ReasonPhrase); }
private Task <bool> ComputeContentLengthAsync(HttpRequestMessage request, HttpResponseMessage response, IOwinResponse owinResponse, CancellationToken cancellationToken) { Contract.Assert(response != null); HttpResponseHeaders responseHeaders = response.Headers; Contract.Assert(responseHeaders != null); HttpContent content = response.Content; Contract.Assert(content != null); HttpContentHeaders contentHeaders = content.Headers; Contract.Assert(contentHeaders != null); Exception exception; try { var unused = contentHeaders.ContentLength; return(Task.FromResult(true)); } catch (Exception ex) { exception = ex; } return(HandleTryComputeLengthExceptionAsync(exception, request, response, owinResponse, cancellationToken)); }
private static Task SendResponseMessageAsync(HttpResponseMessage response, IOwinResponse owinResponse) { owinResponse.StatusCode = (int)response.StatusCode; owinResponse.ReasonPhrase = response.ReasonPhrase; // Copy non-content headers IDictionary <string, string[]> responseHeaders = owinResponse.Headers; foreach (KeyValuePair <string, IEnumerable <string> > header in response.Headers) { responseHeaders[header.Key] = header.Value.AsArray(); } HttpContent responseContent = response.Content; if (responseContent == null) { // Set the content-length to 0 to prevent the server from sending back the response chunked responseHeaders["Content-Length"] = new string[] { "0" }; return(TaskHelpers.Completed()); } else { // Copy content headers foreach (KeyValuePair <string, IEnumerable <string> > contentHeader in responseContent.Headers) { responseHeaders[contentHeader.Key] = contentHeader.Value.AsArray(); } // Copy body return(responseContent.CopyToAsync(owinResponse.Body)); } }
public StaticFileContext(IOwinContext context, StaticFileOptions options, PathString matchUrl) { _context = context; _options = options; _matchUrl = matchUrl; _request = context.Request; _response = context.Response; _method = null; _isGet = false; _isHead = false; _subPath = PathString.Empty; _contentType = null; _fileInfo = null; _length = 0; _lastModified = new DateTime(); _etag = null; _etagQuoted = null; _lastModifiedString = null; _ifMatchState = PreconditionState.Unspecified; _ifNoneMatchState = PreconditionState.Unspecified; _ifModifiedSinceState = PreconditionState.Unspecified; _ifUnmodifiedSinceState = PreconditionState.Unspecified; _ranges = null; }
private Task ProcessMatchingExpectation(IOwinResponse response, HttpExpectation httpExpectation) { var httpResponseExpectation = httpExpectation.Response; if (httpExpectation.ResponseExpectationCallback != null) { httpResponseExpectation = httpExpectation.ResponseExpectationCallback.Invoke(); } var expectedResults = string.Empty; if (httpResponseExpectation != null) { response.StatusCode = (int)httpResponseExpectation.StatusCode; expectedResults = httpResponseExpectation.ExpectedResult; if (httpResponseExpectation.Headers != null) { foreach (var key in httpResponseExpectation.Headers.AllKeys) { response.Headers.Add(key, new[] { httpResponseExpectation.Headers[key] }); } } } if (response.Headers != null) { response.Headers.Add("Content-Type", new[] { "application/json" }); } Task.Delay(_expect.ResponseTime).Wait(); return(response.WriteAsync(expectedResults)); }
public static void ResponseWrite(IOwinResponse response, string msg) { response.StatusCode = 200; response.ContentType = "application/json"; response.Write(ResponseMessage.GetJson(1, msg)); response.Body = bodyStream; }
protected async Task WriteBadrequestResponse(string message, IOwinResponse response) { var bytes = Encoding.UTF8.GetBytes(message); response.StatusCode = 400; response.ContentType = "plain/text"; response.ContentLength = bytes.Length; await response.WriteAsync(bytes); }
protected static void SetResponseHeaders(int statusCode, string reasonPhrase, IHttpHeaders headers, IOwinResponse response, params string[] except) { response.StatusCode = statusCode; if (!string.IsNullOrEmpty(reasonPhrase)) response.ReasonPhrase = reasonPhrase; headers.CopyTo(response.Headers, except); }
private void convertToCookie(IOwinResponse response) { var outboundValue = outboundFunc(response); if (outboundValue != null) { // todo: only set cookie if different from outbound response.Cookies.Append(this.cookieName, outboundValue); } }
public OwinContext(IDictionary<string, object> data) { this.data = data; request = new OwinRequest(data); response = new OwinResponse(data); ssl = new OwinSsl(data); host = new OwinHost(data); server = new OwinServer(data); }
public static void SetsCookie(IOwinResponse response, string name, string expectedValue) { // Get the cookie var cookie = GetCookie(response, name); // Check the value Assert.NotNull(cookie); Assert.Equal(expectedValue, cookie.Value); }
string extractSessionFromResponse(IOwinResponse response) { if(response.Environment.ContainsKey(this.environmentKey) == false) { return null; } string outboundSession = response.Environment[this.environmentKey].ToString(); string signedSession = sign(outboundSession, this.passphrase); return signedSession; }
protected override void WriteResponse(IOwinResponse response) { foreach (var resourceName in _resourceNames) { WriteResource( response, _assembly, string.Format("{0}.{1}", _baseNamespace, resourceName)); } }
public async Task<WebApiLogger> ExtractResponseParameters(IOwinResponse response) { Console.WriteLine("ExtractResponseParameters"); logEntry.ResponseContentType = response.ContentType; logEntry.ResponseHeaders = await response.ResponseHeadersToJsonString(); logEntry.ResponseStatusCode = response.StatusCode; logEntry.ResponseContentBody = await response.ResponseBodyToString(); Console.WriteLine("ExtractResponseParameters End"); return this; }
public void Assign(RazorPage parentPage) { Request = parentPage.Request; Response = parentPage.Response; AppPath = parentPage.AppPath; Storage = parentPage.Storage; Url = parentPage.Url; GenerationTime = parentPage.GenerationTime; }
public void Log(IOwinRequest request, IOwinResponse response, long responseTime) { var username = (string.IsNullOrEmpty(request.User?.Identity?.Name)) ? "-" : request.User.Identity.Name; var queryString = string.IsNullOrEmpty(request.QueryString.Value) ? "-" : request.QueryString.Value; var useragent = (request.Headers.Get("User-Agent") ?? "-").Replace(' ', '+'); var referer = request.Headers.Get("Referer") ?? "-"; var message = $"{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} {ApplicationName} {ComputerName} {request.LocalIpAddress} {request.Method} {request.Uri.GetLeftPart(UriPartial.Path)} {queryString} {request.LocalPort} {username} {request.RemoteIpAddress} {useragent} {referer} {response.StatusCode} 0 0 {responseTime}"; RequestLog.Warn(message); }
public static void DeletesCookie(IOwinResponse response, string name) { // Get the cookie var cookie = GetCookie(response, name); // Check the value and expiry Assert.NotNull(cookie); Assert.True(String.IsNullOrEmpty(cookie.Value)); Assert.True(cookie.Fields.ContainsKey("expires")); Assert.Equal(CookieEpoch, DateTimeOffset.Parse(cookie.Fields["expires"])); }
internal static async Task WriteTo(IOwinResponse response, ResponsePayload payload) { var payloadAsJson = JsonConvert.SerializeObject(new { token = payload.Token }, JsonSerializerSettingsFactory.CreateDefault()); response.ContentType = "application/json"; var writer = new StreamWriter(response.Body); await writer.WriteAsync(payloadAsJson); await writer.FlushAsync(); }
public StaticCompressionContext(IDictionary<string, object> environment, StaticCompressionOptions options, IEncoding encoding, ICompressedStorage storage) { _environment = environment; _options = options; _encoding = encoding; _encodingSuffix = "^" + _encoding.Name; _encodingSuffixQuote = "^" + _encoding.Name + "\""; _storage = storage; _request = new OwinRequest(environment); _response = new OwinResponse(environment); }
private static async Task LogResponse(IOwinResponse response) { var respLog = new { StatusCode = response.StatusCode, Headers = response.Headers, Body = await response.ReadBodyAsStringAsync() }; Logger.Debug("HTTP Response" + Environment.NewLine + LogSerializer.Serialize(respLog)); }
private Task ProcessMatchingExpectation(IOwinResponse response, HttpExpectation httpExpectation) { foreach (var key in httpExpectation.Response.Headers.AllKeys) response.Headers.Add(key, new[] { httpExpectation.Response.Headers[key] }); response.Headers.Add("Content-Type", new[] { "application/json" }); response.StatusCode = (int)httpExpectation.Response.StatusCode; Task.Delay(_expect.ResponseTime).Wait(); return response.WriteAsync(httpExpectation.Response.ExpectedResult); }
public static void SetState(RegisteredClient rc, IOwinResponse response) { // Save the cookie state Byte[] identity = Encoding.UTF8.GetBytes(rc.Identity); Byte[] encrypted = MachineKey.Protect(identity, "ShootR.Identity"); var temp = new RegisteredClient(rc.RegistrationID, HttpServerUtility.UrlTokenEncode(encrypted), rc.DisplayName, rc.Photo); var state = JsonConvert.SerializeObject(temp); response.Cookies.Append("shootr.state", state, new CookieOptions { Expires = DateTime.Now.AddDays(30) }); }
protected void WriteResource(IOwinResponse response, Assembly assembly, string resourceName) { using (var inputStream = assembly.GetManifestResourceStream(resourceName)) { if (inputStream == null) { throw new ArgumentException(string.Format( @"Resource with name {0} not found in assembly {1}.", resourceName, assembly)); } inputStream.CopyTo(response.Body); } }
private void SetContentType(string filePath, IOwinResponse response) { var extension = Path.GetExtension(filePath).ToLowerInvariant(); string contentType; if (_contentTypeByExtension.TryGetValue(extension, out contentType)) { response.ContentType = contentType; } else { response.ContentType = "text/plain"; } }
protected void WriteServerError(string message, IOwinResponse response, ILog log) { try { var bytes = Encoding.UTF8.GetBytes(message); response.StatusCode = 500; response.ContentType = "plain/text"; response.ContentLength = bytes.Length; response.Write(bytes); } catch (Exception ex) { log.Error("Error while generating ISE:", ex); } }
private static IEnumerable<Cookie> GetCookies(IOwinResponse response) { foreach (var cookieHeader in response.Headers.GetValues("Set-Cookie")) { var match = _cookieRegex.Match(cookieHeader); if (match.Success) { var fieldStrings = match.Groups["fields"].Value.Split(';'); yield return new Cookie( match.Groups["name"].Value, match.Groups["val"].Value, fieldStrings .Select(s => _fieldRegex.Match(s)) .Where(m => m.Success) .ToDictionary( m => m.Groups["name"].Value, m => m.Groups["val"].Value)); } } }
protected void WriteResource(IOwinResponse response, Assembly assembly, string resourceName) { using (var inputStream = assembly.GetManifestResourceStream(resourceName)) { if (inputStream == null) { throw new ArgumentException(string.Format( @"Resource with name {0} not found in assembly {1}.", resourceName, assembly)); } var buffer = new byte[Math.Min(inputStream.Length, 4096)]; var readLength = inputStream.Read(buffer, 0, buffer.Length); while (readLength > 0) { response.Write(buffer, 0, readLength); readLength = inputStream.Read(buffer, 0, buffer.Length); } } }
public void SetUpContext() { nextMock = new Mock<OwinMiddleware>((OwinMiddleware)null); next = nextMock.Object; requestMock = new Mock<IOwinRequest>(); requestMock.SetupProperty(m => m.User); request = requestMock.Object; responseMock = new Mock<IOwinResponse>(); responseMock.SetupProperty(m => m.StatusCode); responseMock.SetupProperty(m => m.ReasonPhrase); response = responseMock.Object; contextMock = new Mock<IOwinContext>(); contextMock.SetupGet(m => m.Request).Returns(requestMock.Object); contextMock.SetupGet(m => m.Response).Returns(responseMock.Object); context = contextMock.Object; user = new ApiUserPrincipal(new GenericIdentity("T-Rex"), new[] { Role1 }); }
private static Task SendResponseMessageAsync(HttpResponseMessage response, IOwinResponse owinResponse) { owinResponse.StatusCode = (int)response.StatusCode; owinResponse.ReasonPhrase = response.ReasonPhrase; // Copy non-content headers IDictionary<string, string[]> responseHeaders = owinResponse.Headers; foreach (KeyValuePair<string, IEnumerable<string>> header in response.Headers) { responseHeaders[header.Key] = header.Value.AsArray(); } HttpContent responseContent = response.Content; if (responseContent == null) { // Set the content-length to 0 to prevent the server from sending back the response chunked responseHeaders["Content-Length"] = new string[] { "0" }; return TaskHelpers.Completed(); } else { // Copy content headers foreach (KeyValuePair<string, IEnumerable<string>> contentHeader in responseContent.Headers) { responseHeaders[contentHeader.Key] = contentHeader.Value.AsArray(); } // Copy body return responseContent.CopyToAsync(owinResponse.Body); } }
protected virtual void WriteResponse(IOwinResponse response) { WriteResource(response, _assembly, _resourceName); }
public ResponseRelay(IOwinResponse owinResponse) { _owinResponse = owinResponse; }
public OwinResponseMessage(IOwinResponse response) : base(response.Body, response.ContentType) { this.response = response; }
/// <summary> /// Processes incoming request. /// </summary> public async void ProcessRequest() { try { // invalid connection, skip if (!_client.CanRead) return; var rawHeaders = Http11Helper.ReadHeaders(_client); Http2Logger.LogDebug("Http1.1 Protocol Handler. Process request " + string.Join(" ", rawHeaders)); // invalid connection, skip if (rawHeaders == null || rawHeaders.Length == 0) return; // headers[0] contains METHOD, URI and VERSION like "GET /api/values/1 HTTP/1.1" var headers = Http11Helper.ParseHeaders(rawHeaders.Skip(1).ToArray()); // client MUST include Host header due to HTTP/1.1 spec if (!headers.ContainsKey("Host")) { throw new ApplicationException("Host header is missing"); } // parse request parameters: method, path, host, etc var splittedRequestString = rawHeaders[0].Split(' '); var method = splittedRequestString[0]; if (!IsMethodSupported(method)) { throw new NotSupportedException(method + " method is not currently supported via HTTP/1.1"); } var scheme = _protocol == SslProtocols.None ? Uri.UriSchemeHttp : Uri.UriSchemeHttps; var path = splittedRequestString[1]; // main OWIN environment components // OWIN request and response below shares the same environment dictionary instance _environment = CreateOwinEnvironment(method, scheme, "", path, headers); _request = new OwinRequest(_environment); _response = new OwinResponse(_environment); // we may need to populate additional fields if request supports UPGRADE AddOpaqueUpgradeIfNeeded(); await _next.Invoke(new OwinContext(_environment)); if (_opaqueCallback == null) { EndResponse(); } else { // do not close connection EndResponse(false); var opaqueEnvironment = CreateOpaqueEnvironment(); await _opaqueCallback(new OwinContext(opaqueEnvironment)); } } catch (Exception ex) { Http2Logger.LogError(ex.Message); EndResponse(ex); Http2Logger.LogDebug("Closing connection"); _client.Close(); } }