public void Soap12Parser_ParsesHeaderAndBody(string soap, string expectedAction) { var requestStream = new MemoryStream(Encoding.UTF8.GetBytes(soap)); var action = HttpRequestExtensions.GetSoap12ActionInternal(requestStream); action.Should().Be(expectedAction); }
public void IP_With_Port() { string testValue = "109.87.9.250:56895"; var result = HttpRequestExtensions.GetIPFromHeaderValue(testValue); Assert.AreEqual("109.87.9.250", result); }
/// <summary> /// Sends an HTTP request to the inner handler to send to the server as an asynchronous operation. /// </summary> /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1" />. The task object representing the asynchronous operation. /// </returns> /// <param name="request">The HTTP request message to send to the server.</param> /// <param name="cancellationToken">A cancellation token to cancel operation.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="request" /> was null.</exception> public async Task Invoke(HttpContext context) { if (HasAuthorizationHeader(context.Request, NBAuthScheme.Bearer) && context.Request.Headers["X-NB-Authorization"] != StringValues.Empty) { this.AuthorizeUserViaBearerToken(context.Request); } else if (this.GovernmentServerPublicKey != null && HasAuthorizationHeader(context.Request, NBAuthScheme.NBInternalAuth)) { this.AuthorizeApplicationViaAuthToken(context.Request); } else if (UseSwaggerAsApplicationForDev && this.IsFromSwagger(context.Request)) { this.AuthorizeApplicationIfFromSwagger(); } else if (this.IsFromWhitelists(context.Request)) { this.AuthorizeApplicationIfFromWhitelistst(context.Request); } else if (HttpRequestExtensions.IsFromLocalhost(context)) { this.AuthorizeApplicationIfFromLocalhost(); } if (HasAuthorizationHeader(context.Request) && context.Request.Headers["X-NB-Authorization"] == StringValues.Empty && this.Identity != null && this.Identity.IsAuthenticated && this.Identity.AuthenticationType == NBAuthScheme.Bearer && context.Response.StatusCode == (int)HttpStatusCode.OK) { await this.GenerateAndSetAccessToken(context); } await this._next.Invoke(context); }
/// <summary> /// Parses content from a file on disk from Markdown to HTML. /// </summary> /// <param name="filename">A physical or virtual filename path. If running under System.Web this method uses MapPath to resolve paths. /// For non-HttpContext environments this file name needs to be fully qualified.</param> /// <param name="usePragmaLines">Generates line numbers as ids into headers and paragraphs. Useful for previewers to match line numbers to rendered output</param> /// <param name="forceReload">Forces the parser to reloaded. Otherwise cached instance is used</param> /// <param name="sanitizeHtml">Strips out scriptable tags and attributes for prevent XSS attacks. Minimal implementation.</param> /// <returns>HTML result as a string</returns> public static async Task <string> ParseFromFileAsync(string markdownFile, bool usePragmaLines = false, bool forceReload = false, bool sanitizeHtml = false) { if (string.IsNullOrEmpty(markdownFile)) { return(markdownFile); } var context = MarkdownComponentState.GetHttpContext(); var filename = HttpRequestExtensions.MapPath(context.Request, markdownFile); string content = null; try { using (var reader = File.OpenText(filename)) { content = await reader.ReadToEndAsync(); } } catch (Exception ex) { throw new FileLoadException("Couldn't load Markdown file: " + Path.GetFileName(markdownFile), ex); } return(Parse(content, usePragmaLines, forceReload, sanitizeHtml)); }
public void GetHttpMethodOverrideWithNullRequestThrows() { // Act & Assert ExceptionHelper.ExpectArgumentNullException( delegate { HttpRequestExtensions.GetHttpMethodOverride(null); }, "request"); }
/// <summary> /// Parses content from a file on disk from Markdown to HTML. /// </summary> /// <param name="filename">A physical or virtual filename path. If running under System.Web this method uses MapPath to resolve paths. /// For non-HttpContext environments this file name needs to be fully qualified.</param> /// <param name="usePragmaLines">Generates line numbers as ids into headers and paragraphs. Useful for previewers to match line numbers to rendered output</param> /// <param name="forceReload">Forces the parser to reloaded. Otherwise cached instance is used</param> /// <param name="sanitizeHtml">Strips out scriptable tags and attributes for prevent XSS attacks. Minimal implementation.</param> /// <returns>HTML result as a string</returns> public static string ParseFromFile(string markdownFile, bool usePragmaLines = false, bool forceReload = false, bool sanitizeHtml = false) { if (string.IsNullOrEmpty(markdownFile)) { return(markdownFile); } string filename; var context = MarkdownComponentState.GetHttpContext(); filename = HttpRequestExtensions.MapPath(context.Request, markdownFile); string markdown = null; try { using (var reader = File.OpenText(filename)) { markdown = reader.ReadToEnd(); } } catch (Exception ex) { throw new FileLoadException("Couldn't load Markdown file: " + Path.GetFileName(markdownFile), ex); } var parser = MarkdownComponentState.Configuration.MarkdownParserFactory.GetParser(); var html = parser.Parse(markdown, sanitizeHtml); return(html); }
public void Normal_IP() { string testValue = "109.87.9.250"; var result = HttpRequestExtensions.GetIPFromHeaderValue(testValue); Assert.AreEqual(testValue, result); }
public void TestGetUriThrowsExceptionOnNullRequestObject() { Assert.Throws <ArgumentNullException>( () => { HttpRequestExtensions.GetUri(null); }); }
public void GetHttpMethodOverrideWithNullRequestThrows() { // Act & Assert Assert.ThrowsArgumentNull( () => HttpRequestExtensions.GetHttpMethodOverride(null), "request" ); }
/// <summary> /// Process markdown and generate HTML output /// </summary> /// <param name="context"></param> /// <param name="output"></param> /// <returns></returns> public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { await base.ProcessAsync(context, output); string content = null; if (!string.IsNullOrEmpty(Filename)) { try { var filename = HttpRequestExtensions.MapPath(_httpContext.HttpContext.Request, Filename); using (var reader = File.OpenText(filename)) { content = await reader.ReadToEndAsync(); } } catch (Exception ex) { throw new FileLoadException("Couldn't load Markdown file: " + Path.GetFileName(Filename), ex); } if (string.IsNullOrEmpty(content)) { return; } } else { if (Markdown != null) { content = Markdown.Model?.ToString(); } if (content == null) { content = (await output.GetChildContentAsync(NullHtmlEncoder.Default)) .GetContent(NullHtmlEncoder.Default); } if (string.IsNullOrEmpty(content)) { return; } content = content.Trim('\n', '\r'); } string markdown = NormalizeWhiteSpaceText(content); var parser = MarkdownParserFactory.GetParser(); var html = parser.Parse(markdown, SanitizeHtml); output.TagName = null; // Remove the <markdown> element output.Content.SetHtmlContent(html); }
public void Given_InvalidMethod_When_GetShortenerRequestAsync_Invoked_Then_It_Should_Throw_Exception(string method) { var req = new Mock <HttpRequest>(); req.SetupGet(p => p.Method).Returns(method); Func <Task> func = async() => await HttpRequestExtensions.GetShortenerRequestAsync(req.Object).ConfigureAwait(false); func.Should().Throw <InvalidOperationException>(); }
public void PutExecuteTest() { string appKeyName = "loaderio-auth"; string appKey = "05bf62a8dffd7a28436e4d615991608a"; string url = string.Format("https://api.loader.io/v2/tests/{0}/run", "702a39093c578167a4ba001b54714c2f"); string postData = string.Empty; //need to get results id var result = HttpRequestExtensions.TryPutJson <LoaderIoResultTestResultModel>(url, appKeyName, appKey, postData, 300000); }
//http://api.linkedin.com/v1/people/~ public static void RequestAuthorization(WebConsumer consumer) { if (consumer == null) { throw new ArgumentNullException("consumer"); } Uri callback = HttpRequestExtensions.GetUrlRewriter(HttpContext.Current.Request.Headers, Util.GetCallbackUrlFromContext().StripQueryArgumentsWithPrefix("oauth_")); var request = consumer.PrepareRequestUserAuthorization(callback, null, null); consumer.Channel.Send(request); }
public async Task Given_Query_When_GetExpanderRequestAsync_Invoked_Then_It_Should_Return_Result(string method, string shortUrl) { var req = new Mock <HttpRequest>(); req.SetupGet(p => p.Method).Returns(method); var result = await HttpRequestExtensions.GetExpanderRequestAsync(req.Object, shortUrl).ConfigureAwait(false); result.Should().NotBeNull(); result.ShortUrl.Should().Be(shortUrl); }
public async Task ReadBodyAsStringAsync_Empty_Body_Test() { //Arrange var httpRequest = CreateMockRequest(null).Object; //Act var result = await HttpRequestExtensions.ReadBodyAsStringAsync(httpRequest); //Assert Assert.True(string.IsNullOrEmpty(result)); }
public void Given_Null_When_GetExpanderRequestAsync_Invoked_Then_It_Should_Throw_Exception() { var req = new Mock <HttpRequest>(); Func <Task> func = async() => await HttpRequestExtensions.GetExpanderRequestAsync(null, null).ConfigureAwait(false); func.Should().Throw <ArgumentNullException>(); func = async() => await HttpRequestExtensions.GetExpanderRequestAsync(req.Object, null).ConfigureAwait(false); func.Should().Throw <ArgumentNullException>(); }
public void TestGetUriThrowsExceptionOnRequestObjectSchemeIsEmpty() { var request = new DefaultHttpContext().Request; var exception = Assert.Throws <ArgumentException>( () => { HttpRequestExtensions.GetUri(request); }); Assert.True(exception.Message.Contains("Scheme"), "Scheme is not mentioned in the exception"); }
public void TestGetUriUsesDefaultHostNameOnRequestObjectHostIsNotSpecified() { var request = new DefaultHttpContext().Request; request.Scheme = ExpectedSchema; var uri = HttpRequestExtensions.GetUri(request); Assert.Equal( new Uri(string.Format(CultureInfo.InvariantCulture, "{0}://{1}", ExpectedSchema, ExpectedDefaultHostName)), uri); }
public void TestGetUriReturnsCorrectUriIfRequestObjectSchemeAndHostAreSpecified() { var request = new DefaultHttpContext().Request; request.Scheme = ExpectedSchema; request.Host = new HostString(ExpectedHostName); var uri = HttpRequestExtensions.GetUri(request); Assert.Equal( new Uri(string.Format(CultureInfo.InvariantCulture, "{0}://{1}", ExpectedSchema, ExpectedHostName)), uri); }
public void Can_resolve_paths_with_multipart_root() { var results = new List <string> { HttpRequestExtensions.GetPathInfo("/api/foo/metadata", "api/foo", "api"), HttpRequestExtensions.GetPathInfo("/api/foo/1.0/wildcard/metadata", "api/foo/1.0/wildcard", "api"), HttpRequestExtensions.GetPathInfo("/location.api.wildcard35/api/foo/metadata", "api/foo", "api"), HttpRequestExtensions.GetPathInfo("/this/is/very/nested/metadata", "this/is/very/nested", "api"), }; Console.WriteLine(results.Dump()); Assert.That(results.All(x => x == "/metadata")); }
public void TestGetUriUsesMultipleHostNameOnRequestWithManyHostsSpecified() { var request = new DefaultHttpContext().Request; request.Scheme = ExpectedSchema; request.Host = new HostString("host1,host2"); var uri = HttpRequestExtensions.GetUri(request); Assert.Equal( new Uri(string.Format(CultureInfo.InvariantCulture, "{0}://{1}", ExpectedSchema, ExpectedMulltipleHostName)), uri); }
public async Task <FairDTO> AddFair(FairDTO fairDTO) { HttpRequestMessage requestMessage = new HttpRequestMessage() { RequestUri = new Uri("http://localhost:57892/api/Fair/Add"), Method = HttpMethod.Post, Content = HttpRequestExtensions.ContentAsByteJson(fairDTO), }; var response = await _httpClient.SendAsync(requestMessage); var result = HttpResponseExtensions.ContentAsType <FairDTO>(response); return(result); }
/// <summary> /// Login API request /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> internal LoginResultModel FirstUserLogin(string username, string password) { JsonParser jsonParser = new JsonParser(); string URL = "http://" + Constants.MemoryConf["TestingEnvironment"] + "/login/"; var data = new LoginRequest { Password = password, Username = username }; string postData = string.Format("username={0}&password={1}", data.Username, data.Password); var result = HttpRequestExtensions.TryPostJson<LoginResultModel>(URL, postData); return result; }
public void TestGetUriThrowsExceptionOnRequestObjectHostIsNotSpecified() { var request = new DefaultHttpContext().Request; request.Scheme = ExpectedSchema; var exception = Assert.Throws( typeof(ArgumentException), () => { HttpRequestExtensions.GetUri(request); }); Assert.True(exception.Message.Contains("Host"), "Host is not mentioned in the exception"); }
public void TestGetUriReturnsCorrectUriIfRequestObjectSchemeAndHostAndPathAndQueryStringAreSpecified() { var request = new DefaultHttpContext().Request; request.Scheme = ExpectedSchema; request.Host = new HostString(ExpectedHostName); request.Path = new PathString(ExpectedPath); request.QueryString = new QueryString(ExpectedQueryString); var uri = HttpRequestExtensions.GetUri(request); Assert.Equal( new Uri(string.Format("{0}://{1}{2}{3}", ExpectedSchema, ExpectedHostName, ExpectedPath, ExpectedQueryString)), uri); }
public async Task <string> UpdateAsync(InterviewDTO interviewDTO) { HttpRequestMessage requestMessage = new HttpRequestMessage() { RequestUri = new Uri("http://localhost:57892/api/Interview/Update"), Method = HttpMethod.Post, Content = HttpRequestExtensions.ContentAsByteJson(interviewDTO), }; var response = await _httpClient.SendAsync(requestMessage); if (response.StatusCode == HttpStatusCode.OK) { return(await Task.FromResult("Görüşme Güncellendi.")); } return(await Task.FromResult("Görüşme Güncellenemedi.")); }
/// <summary> /// Gets the expiry timestamp. 901 is Android, 902 is IOS /// How long the token will be effective /// </summary> /// <returns>System.Int64.</returns> protected long GetExpiryTimestamp() { int duration = this._authConfig.PCSignInExpirationSeconds; TraceEntry traceEntry = this.Request.GetTraceEntry(); if (traceEntry.ClientId.Contains(this._authConfig.IOSClientId) || traceEntry.ClientId.Contains(this._authConfig.AndroidClientId)) { duration = this._authConfig.AppSignInExpirationSeconds; } else if (HttpRequestExtensions.IsFromMobileDevice(this.HttpContext)) { duration = this._authConfig.MobileSignInExpirationSeconds; } return(DateTime.UtcNow.Add(duration.Seconds()).UnixTimestamp()); }
/// <summary> /// Ips the is authorized. /// </summary> /// <param name="context">The context.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> private bool IpIsAuthorized(AuthorizationFilterContext context) { HttpRequest request = context.HttpContext.Request; string ip = HttpRequestExtensions.GetUserHostAddress(request.HttpContext.Request); if (string.IsNullOrEmpty(ip)) { return(false); } if (this.ValiadIPRegex == null) { return(ip == "::1"); } return(this.ValiadIPRegex.IsMatch(ip) || ip == "::1"); }
public void ConvertUserIdentitiesToJArray_RemovesCircularReference() { IIdentity identity = new TestIdentity(); Claim claim = new Claim("authlevel", "admin", "test", "LOCAL AUTHORITY", "LOCAL AUTHORITY"); List <Claim> claims = new List <Claim>() { claim }; ClaimsIdentity claimsIdentity = new ClaimsIdentity(identity, claims); List <ClaimsIdentity> claimsIdentities = new List <ClaimsIdentity>() { claimsIdentity }; var userIdentitiesString = HttpRequestExtensions.GetUserIdentitiesAsJArray(claimsIdentities); Assert.Contains("TestAuthType", userIdentitiesString[0]["AuthenticationType"].ToString()); }
public RequestAttributes GetRequestAttributes(System.ServiceModel.OperationContext operationContext) { if (!HostContext.Config.EnableAccessRestrictions) { return(default(RequestAttributes)); } var portRestrictions = default(RequestAttributes); var ipAddress = GetIpAddress(operationContext); portRestrictions |= HttpRequestExtensions.GetAttributes(ipAddress); //TODO: work out if the request was over a secure channel //portRestrictions |= request.IsSecureConnection ? PortRestriction.Secure : PortRestriction.InSecure; return(portRestrictions); }