示例#1
0
        private static Task WriteGeneralExceptionResponseAsync(
            HttpContext context,
            bool isDevelopment,
            IExceptionHandlerFeature exceptionFeature,
            Guid exceptionId,
            IHttpConnectionFeature connection)
        {
            var routeData     = context.GetRouteData() ?? new RouteData();
            var actionContext = new ActionContext(context, routeData, new ActionDescriptor());
            var result        = new ObjectResult(new ProblemDetails
            {
                Detail = isDevelopment
                    ? exceptionFeature.Error.StackTrace
                    : "Check logs with the provided traceId",
                Title      = "Error processing the request",
                Status     = (int)HttpStatusCode.InternalServerError,
                Extensions =
                {
                    { "traceId",      exceptionId.ToString()  },
                    { "connectionId", connection.ConnectionId },
                },
            })
            {
                StatusCode = (int)HttpStatusCode.InternalServerError,
            };

            var executor = context.RequestServices
                           .GetRequiredService <IActionResultExecutor <ObjectResult> >();

            return(executor.ExecuteAsync(actionContext, result));
        }
示例#2
0
        public IActionResult Index(string key)
        {
            EtcdClient client = new EtcdClient("etcd", 2379);

            Etcdserverpb.RangeResponse response;
            if (key == null)
            {
                response = client.Get("/foo/foo");
            }
            else
            {
                response = client.Get(key);
            }

            try
            {
                RepeatedField <Mvccpb.KeyValue> kvs        = response.Kvs;
                IEnumerator <Mvccpb.KeyValue>   enumerator = kvs.GetEnumerator();
                enumerator.MoveNext();
                string value = enumerator.Current.Value.ToStringUtf8();

                ViewData["Message"] = "etcd says: " + value;
            }catch (Exception e) {
                ViewData["Message"] = e.ToString();
            }
            IHttpConnectionFeature feature = HttpContext.Features.Get <IHttpConnectionFeature>();

            ViewData["IP"]     = feature.LocalIpAddress.ToString();
            ViewData["Config"] = _configuration["somewhere"];

            client.Put("visited", feature.LocalIpAddress.ToString());

            return(View());
        }
示例#3
0
        public IActionResult ServerIPAddress()
        {
            try
            {
                IHttpConnectionFeature httpConnectionFeature = HttpContext.Features.Get <IHttpConnectionFeature>();

                IPAddress localIpAddress = httpConnectionFeature?.LocalIpAddress;
                int?      localPort      = httpConnectionFeature?.LocalPort;

                IPAddress RemoteIpAddress = httpConnectionFeature?.LocalIpAddress;
                int?      RemotePort      = httpConnectionFeature?.LocalPort;

                dynamic ret_model = new
                {
                    Local    = localIpAddress.MapToIPv4().ToString() + ":" + localPort,
                    Remote   = RemoteIpAddress.MapToIPv4().ToString() + ":" + RemotePort,
                    HostName = Dns.GetHostName()
                };

                return(OkEx(ret_model));
            }
            catch (Exception ex)
            {
                return(NotFound(ex.Message));
            }
        }
 void IFeatureCache.CheckFeaturesRevision()
 {
     if (_cachedFeaturesRevision != _features.Revision)
     {
         _connection = null;
         _tlsConnection = null;
         _cachedFeaturesRevision = _features.Revision;
     }
 }
示例#5
0
 void IFeatureCache.CheckFeaturesRevision()
 {
     if (_cachedFeaturesRevision != _features.Revision)
     {
         _connection             = null;
         _tlsConnection          = null;
         _cachedFeaturesRevision = _features.Revision;
     }
 }
示例#6
0
        } = 16;                                              // IPv6 size, from here https://github.com/dotnet/runtime/blob/26a71f95b708721065f974fd43ba82a1dcb3e8f0/src/libraries/Common/src/System/Net/IPAddressParserStatics.cs#L9

        public bool TryWriteBytes(HttpContext context, Span <byte> span, out int bytesWritten)
        {
            bytesWritten = -1;
            IHttpConnectionFeature connection = context.Features.Get <IHttpConnectionFeature>();
            IPAddress?remoteIpAddress         = connection.RemoteIpAddress;

            return(remoteIpAddress != null &&
                   remoteIpAddress.TryWriteBytes(span, out bytesWritten));
        }
        private static string GetIpAddress(IHttpConnectionFeature httpConnectionFeature)
        {
            if (httpConnectionFeature == null)
            {
                return(string.Empty);
            }

            return(httpConnectionFeature?.RemoteIpAddress?.AddressFamily.ToString() ?? string.Empty);
        }
        private static string GetLocalIpAddress(IHttpConnectionFeature httpConnectionFeature)
        {
            if (httpConnectionFeature == null)
            {
                return(string.Empty);
            }

            return(httpConnectionFeature?.LocalIpAddress?.ToString() ?? string.Empty);
        }
示例#9
0
 private static void UpdateServerPort(HttpContext httpContext, IHttpConnectionFeature connectionFeature)
 {
     if (httpContext.Request.Headers.TryGetValue("X-Forwarded-Port", out var header) &&
         header.Count == 1 &&
         ushort.TryParse(header[0], NumberStyles.None, NumberFormatInfo.InvariantInfo, out var port) &&
         port != 0)
     {
         connectionFeature.LocalIpAddress = IPAddress.Any;
         connectionFeature.LocalPort      = port;
     }
 }
示例#10
0
 private static void UpdateRemoteIpAddress(HttpContext httpContext, IHttpConnectionFeature connectionFeature)
 {
     if (httpContext.Request.Headers.TryGetValue("X-Real-IP", out var header) &&
         header.Count == 1 &&
         IPAddress.TryParse(header[0], out var address) &&
         (address.AddressFamily == AddressFamily.InterNetwork || address.AddressFamily == AddressFamily.InterNetworkV6))
     {
         connectionFeature.RemoteIpAddress = address;
         connectionFeature.RemotePort      = 0;
     }
 }
        public RequestInfo GetRequestInfo(IHttpConnectionFeature httpConnectionFeature)
        {
            RequestInfo serverInfo = new RequestInfo();

            serverInfo.ConnectionId    = httpConnectionFeature.ConnectionId;
            serverInfo.LocalIpAddress  = httpConnectionFeature.LocalIpAddress.MapToIPv4().ToString();
            serverInfo.LocalPort       = httpConnectionFeature.LocalPort;
            serverInfo.RemoteIpAddress = httpConnectionFeature.RemoteIpAddress.MapToIPv4().ToString();
            serverInfo.RemotePort      = httpConnectionFeature.RemotePort;
            return(serverInfo);
        }
示例#12
0
        public string GetKey(HttpContext httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            IHttpConnectionFeature connection = httpContext.Features.Get <IHttpConnectionFeature>();

            return(connection.RemoteIpAddress.ToString());
        }
示例#13
0
        public static string GetClientIPAddress(this HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // https://github.com/aspnet/HttpAbstractions/blob/fee220569aa108078ab0e231080724eb74ec8b2d/src/Microsoft.AspNet.Http/HttpContext.cs#L45-L48
            // https://github.com/aspnet/HttpAbstractions/blob/fee220569aa108078ab0e231080724eb74ec8b2d/src/Microsoft.AspNet.HttpFeature/IHttpConnectionFeature.cs
            IHttpConnectionFeature connection = context.GetFeature <IHttpConnectionFeature>();

            return(connection != null
                ? connection.RemoteIpAddress.ToString()
                : null);
        }
示例#14
0
        private static void UpdateConnectionId(HttpContext httpContext, IHttpConnectionFeature connectionFeature)
        {
            string value;

            if (httpContext.Request.Headers.TryGetValue("X-Connection-ID", out var header) &&
                header.Count == 1 &&
                !string.IsNullOrWhiteSpace(value = header[0]))
            {
                var id = connectionFeature.ConnectionId;
                if (!string.IsNullOrWhiteSpace(id))
                {
                    id = value + ":" + id;
                }

                connectionFeature.ConnectionId = id;
            }
        }
 public void BindRequestInfo(HttpContext httpContext, BaseResponseDto baseResponseDto)
 {
     try
     {
         IHttpConnectionFeature httpConnectionFeature = httpContext.Features.Get <IHttpConnectionFeature>();
         baseResponseDto.ConnectionId    = httpConnectionFeature.ConnectionId;
         baseResponseDto.LocalIpAddress  = httpConnectionFeature.LocalIpAddress.MapToIPv4().ToString();
         baseResponseDto.LocalPort       = httpConnectionFeature.LocalPort;
         baseResponseDto.RemoteIpAddress = httpConnectionFeature.RemoteIpAddress.MapToIPv4().ToString();
         baseResponseDto.RemotePort      = httpConnectionFeature.RemotePort;
         baseResponseDto.RequestPath     = httpContext.Request.Path.Value;
         baseResponseDto.SignedInTime    = httpContext.Session.GetString("SignedInTime");
     }
     catch (Exception)
     {
     }
 }
示例#16
0
        public override Task HandleAsync(ThrottleContext throttleContext, IPExclusion exclusion)
        {
            if (throttleContext == null)
            {
                throw new ArgumentNullException(nameof(throttleContext));
            }

            if (exclusion == null)
            {
                throw new ArgumentNullException(nameof(exclusion));
            }

            IHttpConnectionFeature connection = throttleContext.HttpContext.Features.Get <IHttpConnectionFeature>();

            if (exclusion.Whitelist.Contains(connection.RemoteIpAddress))
            {
                throttleContext.Abort(exclusion);
            }

            return(Constants.CompletedTask);
        }
示例#17
0
        private string GetRemoteAddress()
        {
            const string HeaderXForwardedFor = "X-FORWARDED-FOR";

            StringValues forwardedFor;

            if (HttpContext.Request.Headers.TryGetValue(HeaderXForwardedFor, out forwardedFor))
            {
                string[] addresses = forwardedFor[0].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                return(addresses[0].Trim());
            }

            IHttpConnectionFeature connection = HttpContext.Features.Get <IHttpConnectionFeature>();

            if (connection != null)
            {
                return(connection.RemoteIpAddress.ToString());
            }

            _logger.LogError("Unable to get IHttpConnectionFeature.");
            return(null);
        }
示例#18
0
        /// <summary>
        /// Tries to extract the remote endpoint from the given <see cref="ConnectionContext"/> in a
        /// version agnostic way.
        /// </summary>
        /// <param name="context">The ASP.net core connection context to extract the remote endpoint from.</param>
        /// <returns>The endpoint of the remote party or null if it was not provided.</returns>
        private static IPEndPoint GetRemoteEndPoint(ConnectionContext context)
        {
            // 1st chance: Server might provide remote endpoint via HTTP feature
            // (mostly the case in ASP.net core v2.x)
            IHttpConnectionFeature connectionFeature = context.Features.Get <IHttpConnectionFeature>();

            if (connectionFeature != null)
            {
                return(new IPEndPoint(connectionFeature.RemoteIpAddress, connectionFeature.RemotePort));
            }

            // 2nd chance: on ASP.net core 5.0 the ConnectionContext has a direct Property RemoteEndpoint
            // via baseclass.
            var net5RemoteEndPointPropertyAccessor = s_net5RemoteEndPointPropertyAccessor;

            if (net5RemoteEndPointPropertyAccessor != null)
            {
                return(net5RemoteEndPointPropertyAccessor(context));
            }

            // last chance: server does likely not support access to remote endpoint. could be
            // a non-tcp server like the ASP.net core test server
            return(null);
        }
        public void WriteToLogFile(string category, Core.Log.Logging.LevelEnum level, int relStack, string message)
        {
            if (level == Core.Log.Logging.LevelEnum.Error)
            {
                message += "\n" + GetCallStack(relStack + 1);
            }
            message = message.Truncate(10000); // limit max text

            string moduleName;
            int    siteIdentity = 0;

            int    userId       = 0;
            string userName     = "";
            string ipAddress    = "";
            string referrer     = "";
            string requestedUrl = "";
            string sessionId    = "";

            category = category.Truncate(LogRecord.MaxCategory);
            if (YetaWFManager.HaveManager)
            {
                if (Manager.HaveCurrentSite)
                {
                    siteIdentity = Manager.CurrentSite.Identity;
                }
                userId    = Manager.UserId;
                userName  = Manager.UserName ?? "";
                userName  = userName.Truncate(Globals.MaxUser);
                sessionId = category == YetaWF.Core.Log.Logging.YetaWFEvent ? Manager.CurrentSessionId : "";
            }
            HttpContext httpContext = YetaWFManager.HttpContextAccessor.HttpContext;

            if (httpContext != null)
            {
                // We don't have a Manager for certain log records (particularly during startup)
                HttpRequest req = httpContext.Request;
                if (req != null)
                {
                    requestedUrl = req.GetDisplayUrl();
                    IHttpConnectionFeature connectionFeature = httpContext.Features.Get <IHttpConnectionFeature>();
                    if (connectionFeature != null)
                    {
                        ipAddress = connectionFeature.RemoteIpAddress.ToString();
                    }
                    referrer     = req.Headers["Referer"].ToString();
                    requestedUrl = requestedUrl ?? "";
                    requestedUrl = requestedUrl.Truncate(Globals.MaxUrl);
                    referrer     = referrer ?? "";
                    referrer     = referrer.Truncate(Globals.MaxUrl);
                    ipAddress    = ipAddress ?? "";
                    ipAddress    = ipAddress.Truncate(Globals.MaxIP);
                }
            }
            MethodBase methBase = null;

            moduleName = null;
#if DEBUG
            GetCallInfo(relStack + 3, out moduleName);// this is really slow
#endif

            SaveMessage(new LogRecord {
                Category     = category,
                Level        = level,
                Info         = message,
                TimeStamp    = DateTime.UtcNow,
                SessionId    = sessionId,
                ModuleName   = moduleName,
                Class        = methBase == null ? "" : (methBase.DeclaringType != null) ? methBase.DeclaringType.Name : "",
                Method       = methBase == null ? "" : methBase.Name,
                Namespace    = methBase == null ? "" : (methBase.DeclaringType != null) ? methBase.DeclaringType.Namespace : "",
                SiteIdentity = siteIdentity,
                UserId       = userId,
                UserName     = userName,
                IPAddress    = ipAddress,
                RequestedUrl = requestedUrl,
                ReferrerUrl  = referrer,
            });
        }
示例#20
0
 /// <summary>
 /// This method is called after the APIGatewayProxyFunction has marshalled the incoming API Gateway request
 /// into ASP.NET Core's IHttpConnectionFeature. Derived classes can overwrite this method to alter
 /// the how the marshalling was done.
 /// </summary>
 /// <param name="aspNetCoreConnectionFeature"></param>
 /// <param name="apiGatewayRequest"></param>
 /// <param name="lambdaContext"></param>
 protected virtual void PostMarshallConnectionFeature(IHttpConnectionFeature aspNetCoreConnectionFeature, APIGatewayProxyRequest apiGatewayRequest, ILambdaContext lambdaContext)
 {
 }
 public KestrelJrpcRequestContext(IHttpRequestFeature requestFeature, IHttpConnectionFeature httpConnectionFeature)
 {
     _requestFeature        = requestFeature;
     _httpConnectionFeature = httpConnectionFeature;
 }
示例#22
0
 public NetStandardRequestContext(HttpContext context)
 {
     _ctx      = context;
     _conn     = _ctx.Features.Get <IHttpConnectionFeature>();
     _headersD = new Lazy <IDictionary <string, string> >(() => RawHeaders.ToDictionary(x => x.Key, y => y.Value.First()));
 }
示例#23
0
 /// <summary>
 /// This method is called after the FcHttpEntrypoint has marshalled the incoming API Gateway request
 /// into ASP.NET Core's IHttpConnectionFeature. Derived classes can overwrite this method to alter
 /// the how the marshalling was done.
 /// </summary>
 /// <param name="aspNetCoreConnectionFeature">ASP net core connection feature.</param>
 /// <param name="request">Request.</param>
 /// <param name="fcContext">Fc context.</param>
 protected virtual void PostMarshallConnectionFeature(IHttpConnectionFeature aspNetCoreConnectionFeature, HttpRequest request, IFcContext fcContext)
 {
 }