Search code examples
c#htmlasp.net-core-mvcip-addresstempdata

How to convert string to IPAddress


I was trying to use tempdata with ip address and when I tried to assign tempdata to an ipaddress variable it said I needed to serialize it so I saw online how to serialize an ip address variable. After implementing it I was running into an issue in my middleware where I made a variable IPAddress ipAddress and assigned it in the if statement for my tempdata.containskey() as `ipAddress = (IPAddress)tempdata.Peek("ipaddress").ToString(); but when debugging I saw that it gave me an exception saying:

System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Net.IPAddress'

So I then changed my IPAddress ipAddress to string ipAddress and now when it hits the ipAddress inside of the if statement for tempdata ipAddress will hold "\"::1\"" . Now is that displaying that as that with two "\"' because I am debugging it? And it really holds the value of "::1"? Just want to make sure I am not getting ipAddress to hold the value like that with the two \'s.

Middleware:

    public class CorrelationIdMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;
        private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
        public CorrelationIdMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, ITempDataDictionaryFactory tempDataDictionaryFactory)
        {
            _next = next;
            _logger = loggerFactory.CreateLogger<CorrelationIdMiddleware>();
            _tempDataDictionaryFactory = tempDataDictionaryFactory;
        }

        public async Task Invoke(HttpContext context)
        {
            string correlationId = null;
            string userName;
            string ipAddress;

            var tempData = _tempDataDictionaryFactory.GetTempData(context);

            var key = context.Request.Headers.Keys.FirstOrDefault(n => n.ToLower().Equals("x-correlation-id"));
            if (!string.IsNullOrWhiteSpace(key))
            {
                correlationId = context.Request.Headers[key];
                _logger.LogInformation("Header contained CorrelationId: {@CorrelationId}", correlationId);
            }
            else
            {
                if (tempData.ContainsKey("username") && tempData.ContainsKey("ipaddress"))
                {
                    userName = tempData.Peek("username").ToString();
                
                    ipAddress = tempData.Peek("ipaddress").ToString();

                    context.Response.Headers.Append("X-username", userName);
                    context.Response.Headers.Append("X-ipAddress", ipAddress);
                }

                correlationId = Guid.NewGuid().ToString();
                _logger.LogInformation("Generated new CorrelationId: {@CorrelationId}", correlationId);
            }
            context.Response.Headers.Append("x-correlation-id", correlationId);
            using (LogContext.PushProperty("CorrelationId", correlationId))
            {
                await _next.Invoke(context);
            }
        }
    }

Solution

  • If that's what you see in the debugger* then your variable really does contain those ", I'd say as a consequence of having serialized to string in a json converter; Json attributes and values are always surrounded by quotes. If you want an IPAddress as a string, it has an overridden ToString method...

    • if what you see in the debug tooltip infuses you with the slashes etc, click the 🔍 to open the text visualiser; what you see there is the true exact string content (what you'd see if you wrote the string to a file and opened it in notepad)