コード例 #1
0
        /// <summary>
        /// Combines the given URI components into a string that is properly encoded for use in HTTP headers.
        /// Note that unicode in the HostString will be encoded as punycode.
        /// </summary>
        /// <param name="scheme">http, https, etc.</param>
        /// <param name="host">The host portion of the uri normally included in the Host header. This may include the port.</param>
        /// <param name="pathBase">The first portion of the request path associated with application root.</param>
        /// <param name="path">The portion of the request path that identifies the requested resource.</param>
        /// <param name="query">The query, if any.</param>
        /// <param name="fragment">The fragment, if any.</param>
        /// <returns></returns>
        public static string BuildAbsolute(
            string scheme,
            HostString host,
            PathString pathBase = new PathString(),
            PathString path = new PathString(),
            QueryString query = new QueryString(),
            FragmentString fragment = new FragmentString())
        {
            var combinedPath = (pathBase.HasValue || path.HasValue) ? (pathBase + path).ToString() : "/";

            var encodedHost = host.ToString();
            var encodedQuery = query.ToString();
            var encodedFragment = fragment.ToString();

            // PERF: Calculate string length to allocate correct buffer size for StringBuilder.
            var length = scheme.Length + SchemeDelimiter.Length + encodedHost.Length
                + combinedPath.Length + encodedQuery.Length + encodedFragment.Length;

            return new StringBuilder(length)
                .Append(scheme)
                .Append(SchemeDelimiter)
                .Append(encodedHost)
                .Append(combinedPath)
                .Append(encodedQuery)
                .Append(encodedFragment)
                .ToString();
        }
コード例 #2
0
ファイル: App.cs プロジェクト: KarlPage/UrlService
        public static UrlResult CreateUrlResult(HostString host, UrlEntry entry)
        {
            var shortUrl = $"{host.Value}/api/{entry.Key.Value}";

            return(new UrlResult {
                ShortUrl = shortUrl, LongUrl = entry.Url
            });
        }
コード例 #3
0
ファイル: LinkGenerator.cs プロジェクト: wserr/AspNetCore
 public abstract string?GetUriByAddress <TAddress>(
     TAddress address,
     RouteValueDictionary values,
     string?scheme,
     HostString host,
     PathString pathBase     = default,
     FragmentString fragment = default,
     LinkOptions?options     = default);
コード例 #4
0
 public string StringBuilderWithBoxing(HostString host, PathString basePath, PathString path, QueryString query)
 => new StringBuilder()
 .Append("https://")
 .Append(host)
 .Append(basePath)
 .Append(path)
 .Append(query)
 .ToString();
コード例 #5
0
        public static string GetAbsolutePathWithAuthorization <T>(HostString RequestHost, int Id, string AdminCode) where T : PageModel
        {
            StringBuilder result = new StringBuilder(GetAbsolutePath <Pages.LoginModel>(RequestHost, Id, AdminCode));

            result.Append($"&RedirectURL={ HttpUtility.HtmlDecode( Get<T>() ) }");

            return(result.ToString());
        }
コード例 #6
0
        /// <summary>
        /// Sends e-mails to users with access to any analysis that ended 24 days prior to the current date and will be deleted after 7 days.
        /// </summary>
        /// <param name="numberOfDays">The number of days for which an analysis is stored in the database.</param>
        /// <param name="numberOfDaysLeft">The number of days until the deletion will take place.</param>
        /// <returns></returns>
        private async Task AlertDelete(string scheme, HostString host, int numberOfDays = 31, int numberOfDaysLeft = 7)
        {
            // Get the limit date.
            var limitDate = DateTime.Today - TimeSpan.FromDays(numberOfDays - numberOfDaysLeft);
            // Get the networks and analyses.
            var networks = _context.Networks
                           .Where(item => item.DateTimeCreated < limitDate);
            var analyses = _context.Analyses
                           .Where(item => item.Status == AnalysisStatus.Stopped || item.Status == AnalysisStatus.Completed || item.Status == AnalysisStatus.Error)
                           .Where(item => item.DateTimeEnded < limitDate)
                           .Concat(networks
                                   .Select(item => item.AnalysisNetworks)
                                   .SelectMany(item => item)
                                   .Select(item => item.Analysis))
                           .Distinct();
            // Get the users.
            var networkUsers = networks
                               .Select(item => item.NetworkUsers)
                               .SelectMany(item => item)
                               .Select(item => item.User);
            var analysisUsers = analyses
                                .Select(item => item.AnalysisUsers)
                                .SelectMany(item => item)
                                .Select(item => item.User);
            // Get the users that have access to the items.
            var users = networkUsers
                        .Concat(analysisUsers);

            // Go over each of the users.
            foreach (var user in users)
            {
                // Send an alert delete analyses e-mail.
                await _emailSender.SendAlertDeleteEmailAsync(new EmailAlertDeleteViewModel
                {
                    Email        = user.Email,
                    DateTime     = DateTime.Today + TimeSpan.FromDays(numberOfDaysLeft),
                    NetworkItems = user.NetworkUsers
                                   .Select(item => item.Network)
                                   .Where(item => networks.Contains(item))
                                   .Select(item => new EmailAlertDeleteViewModel.ItemModel
                    {
                        Id   = item.Id,
                        Name = item.Name,
                        Url  = _linkGenerator.GetUriByPage("/Content/Created/Networks/Details/Index", handler: null, values: new { id = item.Id }, scheme: scheme, host: host)
                    }),
                    AnalysisItems = user.AnalysisUsers
                                    .Select(item => item.Analysis)
                                    .Where(item => analyses.Contains(item))
                                    .Select(item => new EmailAlertDeleteViewModel.ItemModel
                    {
                        Id   = item.Id,
                        Name = item.Name,
                        Url  = _linkGenerator.GetUriByPage("/Content/Created/Analyses/Details/Index", handler: null, values: new { id = item.Id }, scheme: scheme, host: host)
                    }),
                    ApplicationUrl = _linkGenerator.GetUriByPage("/Index", handler: null, values: null, scheme: scheme, host: host)
                });
            }
        }
コード例 #7
0
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        base.Process(context, output);

        if (context.AllAttributes.TryGetAttribute("href", out var attribute))
        {
            var content = attribute.Value switch
            {
                string value => value,
                HtmlString htmlString => htmlString.Value,
                _ => null
            };

            if (content != null)
            {
                if (content.StartsWith("//", StringComparison.OrdinalIgnoreCase))
                {
                    content = ViewContext.HttpContext.Request.Scheme + ":" + content;
                }

                // ignore same site
                if (!content.Contains("://", StringComparison.OrdinalIgnoreCase))
                {
                    return;
                }

                // ignore same site
                if (Uri.TryCreate(content, UriKind.Absolute, out var uri))
                {
                    var host = HostString.FromUriComponent(uri);
                    if (host == ViewContext.HttpContext.Request.Host)
                    {
                        return;
                    }
                }
            }
        }

        if (context.AllAttributes.TryGetAttribute("rel", out attribute))
        {
            var content = attribute.Value switch
            {
                string value => value,
                HtmlString htmlString => htmlString.Value,
                _ => null
            };

            if (content != null && !content.Contains("noopener", StringComparison.OrdinalIgnoreCase))
            {
                output.Attributes.SetAttribute("rel", content + " noopener");
            }
        }
        else
        {
            output.Attributes.Add("rel", "noopener");
        }
    }
}
コード例 #8
0
ファイル: App.cs プロジェクト: KarlPage/UrlService
        /// <summary>
        /// Obtain URL from database using the supplied key.
        /// HostString is used to build full hort URL.
        /// </summary>
        public Result <UrlResult> GetUrl(HostString host, string key)
        {
            var result = UrlKey
                         .FromString(key)
                         .Then(DataService.GetUrl)
                         .Then(entry => CreateUrlResult(host, entry));

            return(result);
        }
コード例 #9
0
ファイル: App.cs プロジェクト: KarlPage/UrlService
        /// <summary>
        /// Add URL to database and return a UrlResult that contains both the original and short URL.
        /// HostString is used to build full short URL.
        /// </summary>
        public Result <UrlResult> AddUrlKey(HostString host, string url)
        {
            var result = UrlEntry
                         .CreateFromUrl(8, url)
                         .Then(DataService.AddShortUrl)
                         .Then(entry => CreateUrlResult(host, entry));

            return(result);
        }
コード例 #10
0
        public void CreateInstances()
        {
            _httpContext = new DefaultHttpContext();
            _httpContext.Request.Scheme      = "http";
            _httpContext.Request.Host        = HostString.FromUriComponent("unit test");
            _httpContext.Request.QueryString = QueryString.Create("querystring", "param");

            _httpContext.Response.Body = new MemoryStream();
        }
コード例 #11
0
ファイル: WebSocketClient.cs プロジェクト: omajid/AspNetCore
        public async Task <WebSocket> ConnectAsync(Uri uri, CancellationToken cancellationToken)
        {
            WebSocketFeature webSocketFeature = null;
            var contextBuilder = new HttpContextBuilder(_application, AllowSynchronousIO, PreserveExecutionContext);

            contextBuilder.Configure(context =>
            {
                var request    = context.Request;
                var scheme     = uri.Scheme;
                scheme         = (scheme == "ws") ? "http" : scheme;
                scheme         = (scheme == "wss") ? "https" : scheme;
                request.Scheme = scheme;
                if (!request.Host.HasValue)
                {
                    request.Host = uri.IsDefaultPort
                        ? new HostString(HostString.FromUriComponent(uri).Host)
                        : HostString.FromUriComponent(uri);
                }
                request.Path     = PathString.FromUriComponent(uri);
                request.PathBase = PathString.Empty;
                if (request.Path.StartsWithSegments(_pathBase, out var remainder))
                {
                    request.Path     = remainder;
                    request.PathBase = _pathBase;
                }
                request.QueryString = QueryString.FromUriComponent(uri);
                request.Headers.Add(HeaderNames.Connection, new string[] { "Upgrade" });
                request.Headers.Add(HeaderNames.Upgrade, new string[] { "websocket" });
                request.Headers.Add(HeaderNames.SecWebSocketVersion, new string[] { "13" });
                request.Headers.Add(HeaderNames.SecWebSocketKey, new string[] { CreateRequestKey() });
                if (SubProtocols.Any())
                {
                    request.Headers.Add(HeaderNames.SecWebSocketProtocol, SubProtocols.ToArray());
                }

                request.Body = Stream.Null;

                // WebSocket
                webSocketFeature = new WebSocketFeature(context);
                context.Features.Set <IHttpWebSocketFeature>(webSocketFeature);

                ConfigureRequest?.Invoke(context.Request);
            });

            var httpContext = await contextBuilder.SendAsync(cancellationToken);

            if (httpContext.Response.StatusCode != StatusCodes.Status101SwitchingProtocols)
            {
                throw new InvalidOperationException("Incomplete handshake, status code: " + httpContext.Response.StatusCode);
            }
            if (webSocketFeature.ClientWebSocket == null)
            {
                throw new InvalidOperationException("Incomplete handshake");
            }

            return(webSocketFeature.ClientWebSocket);
        }
コード例 #12
0
        /// <summary>
        /// Builds the HTTP context.
        /// </summary>
        /// <param name="routeEndpoint">The route endpoint.</param>
        /// <param name="requestInfo">The request information.</param>
        /// <param name="routeValues">The route values.</param>
        /// <returns>The HTTP context to invoke a request delegate with</returns>
        private HttpContext BuildHttpContext(RouteEndpoint routeEndpoint, RequestInfo requestInfo, RouteValueDictionary routeValues)
        {
            DefaultHttpContext httpContext = new DefaultHttpContext();

            httpContext.Features.Set <IEndpointFeature>(new HttpContextFeatures.EndpointFeature(routeEndpoint));
            httpContext.Features.Set <IRoutingFeature>(new HttpContextFeatures.RoutingFeature(routeValues));
            httpContext.RequestServices = _serviceProvider;

            if (_httpContextAccessor.HttpContext != null)
            {
                httpContext.User = _httpContextAccessor.HttpContext.User;
            }

            string[] relativeUriComponents = requestInfo.RelativeUri.Split(QuerySeparator);
            Uri      requestUri            = new UriBuilder(_batchRequestOptions.RequestHost)
            {
                Path  = relativeUriComponents[0],
                Query = relativeUriComponents.Length > 1 ? relativeUriComponents[1] : string.Empty,
            }.Uri;

            httpContext.Request.Scheme      = requestUri.Scheme;
            httpContext.Request.Host        = HostString.FromUriComponent(requestUri);
            httpContext.Request.Path        = PathString.FromUriComponent(requestUri);
            httpContext.Request.QueryString = QueryString.FromUriComponent(requestUri);
            httpContext.Request.Query       = new QueryCollection(QueryHelpers.ParseQuery(requestUri.Query));
            httpContext.Request.ContentType = requestInfo.ContentType;
            httpContext.Request.Method      = requestInfo.Method.ToUpper();
            httpContext.Request.Protocol    = _batchRequestOptions.DefaultProtocol;
            httpContext.Request.IsHttps     = httpContext.Request.Scheme == Uri.UriSchemeHttps;

            httpContext.Response.Body = new MemoryStream();
            if (!string.IsNullOrEmpty(requestInfo.Body))
            {
                byte[] bodyData;
                if (requestInfo.Base64Encoded)
                {
                    try
                    {
                        bodyData = Convert.FromBase64String(requestInfo.Body);
                    }
                    catch (FormatException)
                    {
                        throw new Base64FormatException()
                              {
                                  Base64 = requestInfo.Body
                              };
                    }
                }
                else
                {
                    bodyData = Encoding.UTF8.GetBytes(requestInfo.Body);
                }
                httpContext.Request.Body = new MemoryStream(bodyData);
            }

            return(httpContext);
        }
コード例 #13
0
ファイル: Feature.cs プロジェクト: lqt1912/CoStudy.WebAPI
        public static string GetHostUrl(IHttpContextAccessor httpContextAccessor)
        {
            string     scheme   = httpContextAccessor.HttpContext.Request.Scheme;
            HostString host     = httpContextAccessor.HttpContext.Request.Host;
            PathString pathBase = httpContextAccessor.HttpContext.Request.PathBase;
            string     location = $"{scheme}://{host}{pathBase}";

            return(location);
        }
コード例 #14
0
ファイル: UriHelperTests.cs プロジェクト: wserr/AspNetCore
        public void BuildAbsoluteNullInputThrowsArgumentNullException()
        {
            var resHost     = new HostString();
            var resPath     = new PathString();
            var resQuery    = new QueryString();
            var resFragment = new FragmentString();

            Assert.Throws <ArgumentNullException>(() => UriHelper.BuildAbsolute(null, resHost, resPath, resPath, resQuery, resFragment));
        }
コード例 #15
0
        public RedisContext(HostString host)
        {
            var addresses     = Dns.GetHostAddressesAsync(host.Host).Result.Select(addr => addr.MapToIPv4());
            var configuration = host.Port == null
                ? string.Join(",", addresses)
                : string.Join(",", addresses.Select(addr => $"{addr}:{host.Port}"));

            _connection = ConnectionMultiplexer.Connect(configuration);
        }
コード例 #16
0
 public UriHelper(Uri uri)
 {
     Scheme = uri.Scheme;
     Host   = HostString.FromUriComponent(uri);
     // Assume nothing is being put in PathBase
     Path     = PathString.FromUriComponent(uri);
     Query    = QueryString.FromUriComponent(uri);
     Fragment = FragmentString.FromUriComponent(uri);
 }
コード例 #17
0
        private async Task <HttpRequest> GetRequest(HttpContext context, HttpRequestMessage request)
        {
            var requestContent = request.Content ?? new StreamContent(Stream.Null);
            var body           = await requestContent.ReadAsStreamAsync();

            PathString pathBase = new PathString("");

            var req = context.Request;

            req.Protocol = "HTTP/" + request.Version.ToString(fieldCount: 2);
            req.Method   = request.Method.ToString();

            req.Scheme = request.RequestUri.Scheme;

            foreach (var header in request.Headers)
            {
                req.Headers.Append(header.Key, header.Value.ToArray());
            }

            if (req.Host == null || !req.Host.HasValue)
            {
                // If Host wasn't explicitly set as a header, let's infer it from the Uri
                req.Host = HostString.FromUriComponent(request.RequestUri);
                if (request.RequestUri.IsDefaultPort)
                {
                    req.Host = new HostString(req.Host.Host);
                }
            }

            req.Path     = PathString.FromUriComponent(request.RequestUri);
            req.PathBase = PathString.Empty;
            if (req.Path.StartsWithSegments(pathBase, out var remainder))
            {
                req.Path     = remainder;
                req.PathBase = pathBase;
            }
            req.QueryString = QueryString.FromUriComponent(request.RequestUri);

            if (requestContent != null)
            {
                foreach (var header in requestContent.Headers)
                {
                    req.Headers.Append(header.Key, header.Value.ToArray());
                }
            }

            if (body.CanSeek)
            {
                // This body may have been consumed before, rewind it.
                body.Seek(0, SeekOrigin.Begin);
            }
            req.Body = body;


            return(req);
        }
        public string DetermineRedirectURLDueToCulture(HttpContext httpContext)
        {
            var request   = httpContext.Request;
            var host      = request.Host;
            var subdomain = "";

            HostString newHost;

            //First Cookie
            httpContext.Request.Cookies.TryGetValue(CookieRequestCultureProvider.DefaultCookieName, out string cultureCookie);
            var currentCulture = CookieRequestCultureProvider.ParseCookieValue(cultureCookie);

            if (currentCulture != null && currentCulture.Cultures.Count > 0)
            {
                if (currentCulture.Cultures.First().Value == "tr-TR")
                {
                    subdomain = "tr";
                }
                else
                {
                    subdomain = "en";
                }
            }
            else
            {
                //Second GeoLocation
                var country = DetermineCountryDueToIpAddress(httpContext);
                if (!string.IsNullOrEmpty(country))
                {
                    if (country == "TR")
                    {
                        subdomain = "tr";
                    }
                    else
                    {
                        subdomain = "en";
                    }
                }
                // Last to default
                else
                {
                    subdomain = "en";
                }
            }

            if (host.Port.HasValue)
            {
                newHost = new HostString(subdomain + "." + domain, host.Port.Value);
            }
            else
            {
                newHost = new HostString(subdomain + "." + domain);
            }

            return(UriHelper.BuildAbsolute(request.Scheme, newHost, request.PathBase, request.Path, request.QueryString));
        }
コード例 #19
0
 /// <summary>
 /// Combines the given URI components into a string that is properly encoded for use in HTTP headers.
 /// Note that unicode in the HostString will be encoded as punycode.
 /// </summary>
 /// <param name="scheme"></param>
 /// <param name="host"></param>
 /// <param name="pathBase"></param>
 /// <param name="path"></param>
 /// <param name="query"></param>
 /// <param name="fragment"></param>
 /// <returns></returns>
 public static string Encode(string scheme,
     HostString host,
     PathString pathBase = new PathString(),
     PathString path = new PathString(),
     QueryString query = new QueryString(),
     FragmentString fragment = new FragmentString())
 {
     string combinePath = (pathBase.HasValue || path.HasValue) ? (pathBase + path).ToString() : "/";
     return scheme + "://" + host + combinePath + query + fragment;
 }
コード例 #20
0
ファイル: UriHelperTests.cs プロジェクト: wserr/AspNetCore
        public void FromAbsoluteNullInputThrowsArgumentNullException()
        {
            string resScheme   = null;
            var    resHost     = new HostString();
            var    resPath     = new PathString();
            var    resQuery    = new QueryString();
            var    resFragment = new FragmentString();

            Assert.Throws <ArgumentNullException>(() => UriHelper.FromAbsolute(null, out resScheme, out resHost, out resPath, out resQuery, out resFragment));
        }
コード例 #21
0
        public static ProxyOptions GetProxyOptions(this IConfigurationSection config)
        {
            // Host & AppendQuery properties will not bind correctly
            // due to objects being ctor sealed
            var proxyOptions = config.Get <ProxyOptions>();

            proxyOptions.Host        = HostString.FromUriComponent(config["Host"]);
            proxyOptions.AppendQuery = QueryString.FromUriComponent(config["AppendQuery"]);
            return(proxyOptions);
        }
コード例 #22
0
        public ProxyApplicationService(IHttpContextAccessor context, IOptions <ProxyOptions> options)
        {
            _options = options.Value;

            // Should never fail. Host filtering middleware should short-circuit requests for unknown
            // hosts.
            HostString requestHost = context.HttpContext.Request.Host;

            _activeApplication = _options.Applications.First(app => app.Host.Value == requestHost);
        }
コード例 #23
0
        /// <summary>
        ///     Adds X-Forwarded-* headers to the upstream websocket request
        ///     with an additional PathBase parameter.
        /// </summary>
        public static void AddXForwardedHeaders(this WebSocketClientOptions options)
        {
            var protocol   = options.HttpContext.Request.Scheme;
            var @for       = options.HttpContext.Connection.RemoteIpAddress;
            var host       = options.HttpContext.Request.Headers[HeaderNames.Host];
            var hostString = HostString.FromUriComponent(host);
            var pathBase   = options.HttpContext.Request.PathBase.Value;

            options.AddXForwardedHeaders(@for, hostString, protocol, pathBase);
        }
コード例 #24
0
ファイル: HostnameStrategy.cs プロジェクト: woksin/AspNetCore
        TenantId ResolveTenantIdForAllSegments(HostString host, HostnameStrategyResource configuration)
        {
            var tenantSegment = host.Host;

            if (!configuration.Map.ContainsKey(tenantSegment))
            {
                throw new CouldNotMapTenantSegmentToTenantId(tenantSegment);
            }
            return(configuration.Map[tenantSegment]);
        }
コード例 #25
0
        public MongoUrl Resolve(HostString host)
        {
            var connectionString = _configuration.GetConnectionString(host.ToString());

            if (connectionString == null)
            {
                return(null);
            }

            return(new MongoUrl(connectionString));
        }
コード例 #26
0
ファイル: HostStringTest.cs プロジェクト: pa-at/aspnetcore
    public void Port_ExtractsInvalidPortFromValue(string sourceValue)
    {
        // Arrange
        var hostString = new HostString(sourceValue);

        // Act
        var result = hostString.Port;

        // Assert
        Assert.Null(result);
    }
コード例 #27
0
ファイル: HostStringTest.cs プロジェクト: pa-at/aspnetcore
    public void Port_ExtractsPortFromValue(string sourceValue, int?expectedPort)
    {
        // Arrange
        var hostString = new HostString(sourceValue);

        // Act
        var result = hostString.Port;

        // Assert
        Assert.Equal(expectedPort, result);
    }
コード例 #28
0
ファイル: HostStringTest.cs プロジェクト: pa-at/aspnetcore
    public void Domain_ExtractsHostFromValue(string sourceValue, string expectedDomain)
    {
        // Arrange
        var hostString = new HostString(sourceValue);

        // Act
        var result = hostString.Host;

        // Assert
        Assert.Equal(expectedDomain, result);
    }
コード例 #29
0
        public void DeleteViewResultWithViewModel()
        {
            //Won't work, due to it use global Session["ShoppingCartSession"]
            // Arrange
            ShoppingCart shoppingCart = new ShoppingCart()
            {
                ProductId = 1,
                Unit      = 1
            };
            List <ShoppingCart> shoppingCartList = new List <ShoppingCart>();
            var mockLogger   = new Mock <ILogger <HomeController> >();
            var mockCateRepo = new Mock <ICategoryRepository>();
            var mockProdRepo = new Mock <IProductRepository>();

            var session = new MockHttpSession();
            Mock <HttpContext> mockHttpContext = new Mock <HttpContext>();
            MockHttpSession    mockSession     = new MockHttpSession();

            mockSession["ShoppingCartSession"] = new List <ShoppingCart> {
                shoppingCart
            };

            var request = new Mock <HttpRequest>();

            request.Setup(x => x.Scheme).Returns("http");
            request.Setup(x => x.Host).Returns(HostString.FromUriComponent("http://localhost:44331"));
            request.Setup(x => x.PathBase).Returns(PathString.FromUriComponent("/home"));

            var httpContext = Moq.Mock.Of <HttpContext>(_ =>
                                                        _.Request == request.Object
                                                        );

            //Controller needs a controller context
            var controllerContext = new ControllerContext()
            {
                HttpContext = httpContext,
            };
            //assign context to controller
            var controller = new HomeController(mockLogger.Object, mockProdRepo.Object, mockCateRepo.Object)
            {
                ControllerContext = controllerContext,
            };



            //Action
            //var result = controller.RemoveFromCart(1);

            //
            //var viewResult = Assert.IsType<ViewResult>(result);
            //Assert.Null(viewResult);
            //Assert.Null(viewResult.ViewData.Model);
            //Assert.IsType<ShoppingCart>(viewResult.ViewData.Model);
        }
コード例 #30
0
 private int CurrentSettingsIndex(HostString host)
 {
     if (host.Port == 60000)
     {
         return(0);
     }
     else
     {
         return(1);
     }
 }
コード例 #31
0
        public void Port_ExtractsInvalidPortFromValue(string sourceValue)
        {
            // Arrange
            var hostString = new HostString(sourceValue);

            // Act
            var result = hostString.Port;

            // Assert
            Assert.Equal(null, result);
        }
コード例 #32
0
        public void Port_ExtractsPortFromValue(string sourceValue, int? expectedPort)
        {
            // Arrange
            var hostString = new HostString(sourceValue);

            // Act
            var result = hostString.Port;

            // Assert
            Assert.Equal(expectedPort, result);
        }
コード例 #33
0
        public void Domain_ExtractsHostFromValue(string sourceValue, string expectedDomain)
        {
            // Arrange
            var hostString = new HostString(sourceValue);

            // Act
            var result = hostString.Host;

            // Assert
            Assert.Equal(expectedDomain, result);
        }
コード例 #34
0
        private bool CheckHostInAllowList(IList <StringSegment> allowedHosts, string host)
        {
            if (HostString.MatchesAny(new StringSegment(host), allowedHosts))
            {
                _logger.AllowedHostMatched(host);
                return(true);
            }

            _logger.NoAllowedHostMatched(host);
            return(false);
        }
コード例 #35
0
        public static IOwinRequest SetUrl(this IOwinRequest self, string url)
        {
            Uri uri = new Uri(url);

            self.Scheme      = uri.Scheme;
            self.Host        = HostString.FromUriComponent(uri);
            self.PathBase    = new PathString("");
            self.QueryString = QueryString.FromUriComponent(uri);
            self.Path        = PathString.FromUriComponent(uri);
            return(self);
        }
コード例 #36
0
        public void Ctor_CreatesFromHostAndPort(string sourceHost, int sourcePort, string expectedHost, int expectedPort)
        {
            // Arrange
            var hostString = new HostString(sourceHost, sourcePort);

            // Act
            var host = hostString.Host;
            var port = hostString.Port;

            // Assert
            Assert.Equal(expectedHost, host);
            Assert.Equal(expectedPort, port);
        }
コード例 #37
0
        public void ImplicitStringConverters_WorksWithAdd()
        {
            var scheme = "http";
            var host = new HostString("localhost:80");
            var pathBase = new PathString("/base");
            var path = new PathString("/path");
            var query = new QueryString("?query");
            var fragment = new FragmentString("#frag");

            var result = scheme + "://" + host + pathBase + path + query + fragment;
            Assert.Equal("http://localhost:80/base/path?query#frag", result);

            result = pathBase + path + query + fragment;
            Assert.Equal("/base/path?query#frag", result);

            result = path + "text";
            Assert.Equal("/pathtext", result);
        }
コード例 #38
0
ファイル: UriHelper.cs プロジェクト: EgoDust/HttpAbstractions
 public static string Create(string scheme,
     HostString host,
     PathString pathBase = new PathString(),
     PathString path = new PathString(),
     QueryString query = new QueryString(),
     FragmentString fragment = new FragmentString())
 {
     return new UriHelper()
     {
         Scheme = scheme,
         Host = host,
         PathBase = pathBase,
         Path = path,
         Query = query,
         Fragment = fragment
     }.GetFullUri();
 }
コード例 #39
0
        public void NotEquals(string first, string second)
        {
            HostString firstHost = new HostString(first);
            HostString secondHost = new HostString(second);

            Assert.False(firstHost.Equals(secondHost));
            Assert.False(secondHost.Equals(firstHost));
            Assert.NotEqual(firstHost.GetHashCode(), secondHost.GetHashCode());
            Assert.False(firstHost == secondHost);
            Assert.False(secondHost == firstHost);
            Assert.True(firstHost != secondHost);
            Assert.True(secondHost != firstHost);
        }
コード例 #40
0
 public void ValueRoundTrips(string input)
 {
     HostString host = new HostString(input);
     Assert.Equal(input, host.Value, StringComparer.Ordinal);
 }
コード例 #41
0
 public void VerifyToUriComponent(string input, string expected)
 {
     HostString host = new HostString(input);
     Assert.Equal(expected, host.ToUriComponent(), StringComparer.Ordinal);
 }
コード例 #42
0
ファイル: RequireHttpsAttribute.cs プロジェクト: ymd1223/Mvc
        /// <summary>
        /// Called from <see cref="OnAuthorization"/> if the request is not received over HTTPS. Expectation is
        /// <see cref="AuthorizationFilterContext.Result"/> will not be <c>null</c> after this method returns.
        /// </summary>
        /// <param name="filterContext">The <see cref="AuthorizationFilterContext"/> to update.</param>
        /// <remarks>
        /// If it was a GET request, default implementation sets <see cref="AuthorizationFilterContext.Result"/> to a
        /// result which will redirect the client to the HTTPS version of the request URI. Otherwise, default
        /// implementation sets <see cref="AuthorizationFilterContext.Result"/> to a result which will set the status
        /// code to <c>403</c> (Forbidden).
        /// </remarks>
        protected virtual void HandleNonHttpsRequest(AuthorizationFilterContext filterContext)
        {
            // only redirect for GET requests, otherwise the browser might not propagate the verb and request
            // body correctly.
            if (!string.Equals(filterContext.HttpContext.Request.Method, "GET", StringComparison.OrdinalIgnoreCase))
            {
                filterContext.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
            }
            else
            {
                var optionsAccessor = filterContext.HttpContext.RequestServices.GetRequiredService<IOptions<MvcOptions>>();

                var request = filterContext.HttpContext.Request;

                var host = request.Host;
                if (optionsAccessor.Value.SslPort.HasValue && optionsAccessor.Value.SslPort > 0)
                {
                    // a specific SSL port is specified
                    host = new HostString(host.Host, optionsAccessor.Value.SslPort.Value);
                }
                else
                {
                    // clear the port
                    host = new HostString(host.Host);
                }

                var newUrl = string.Concat(
                    "https://",
                    host.ToUriComponent(),
                    request.PathBase.ToUriComponent(),
                    request.Path.ToUriComponent(),
                    request.QueryString.ToUriComponent());

                // redirect to HTTPS version of page
                filterContext.Result = new RedirectResult(newUrl, Permanent);
            }
        }