WebHelper.GetCurrentIpAddress throws NullReferenceException in Task

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
10 years ago
In a plugin I start a Task using Task.Factory.StartNew. The task does some processing and if it fails, it attempts to log the error using an ILogger (DefaultLogger in this case).

Internally it then calls _webHelper.GetCurrentIpAddress, which fails with a NullReferenceException - even though there's thorough null checking going on:

        public virtual string GetCurrentIpAddress()
        {
            if (_httpContext != null &&
                _httpContext.Request != null &&
                _httpContext.Request.UserHostAddress != null)   // <--- FAILS HERE
                return _httpContext.Request.UserHostAddress;
            
            return string.Empty;
        }

Apparently UserHostAddress throws the NullReferenceException internally, so the explicit null check doesn't help. This could be considered an ASP.NET MVC bug, and a quick-and-dirty fix would be to simply catch and ignore the NullReferenceException.

However, I've posted this under bug reports since the logger should log the error even though an IP can't be retrieved.

Is there a more elegant way to handle this than a try-catch-ignore?
10 years ago
In schedule task, It is not actually invoke any http request. It is only schedule task to call any function in specific time of interval. that's why you are getting NullReferenceException.

If you want to call any URL then make a function that contains webrequest and call that function by schedule task.
10 years ago
I'm not talking about a schecked task, but a System.Threading.Tasks.Task. That is, an asynchronous operation that is started as a part of a request and keeps running after the request has ended and a response has been sent.
10 years ago
Meeh, it just fails.

try
{
  if (_httpContext != null &&
      _httpContext.Request != null &&
      _httpContext.Request.UserHostAddress != null)
    return _httpContext.Request.UserHostAddress;
}
catch (Exception)
{
  // Do nothing, IP address cannot be retrieved.
}


Problem solved.

Also IsCurrentConnectionSecured() and GetUrlReferrer() will fail. Same thing from above and it's solved.

The problem is that the HttpContext throws errors when trying to get certain properties.

System.ArgumentException: Value does not fall within the expected range. at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) at System.Web.Hosting.IIS7WorkerRequest.GetServerVariableInternal(String name) at Nop.Core.WebHelper.GetCurrentIpAddress() at Nop.Services.Logging.DefaultLogger.InsertLog(LogLevel logLevel, String shortMessage, String fullMessage, Customer customer) at Nop.Services.Localization.LocalizationService.GetResource(String resourceKey, Int32 languageId, Boolean logIfNotFound, String defaultValue, Boolean returnEmptyIfNotFound) at Nop.Services.Localization.LocalizationService.GetResource(String resourceKey) 


Any ideas how to solve this?

The problem appears when I'm creating a new thread in a controller action and calling methods on services, for example _orderProcessingService.SetOrderStatus(order, OrderStatus.Complete, true).

If I try to resolve the services inside the threads it doesn't work, specifically the db doesn't update.

For example IOrderProcessingService orderProcessingService = EngineContext.Current.Resolve<IOrderProcessingService>();
10 years ago
Hi,

had the same problem when I was trying to insert a log in a custom HandleErrorAttribute.

I extend ILogger and therefore also the DefaultLogger for a InsertLog method that accepts a HttpContext.

 
public Log InsertLog(LogLevel logLevel, string shortMessage, System.Web.HttpContextBase httpContext, string fullMessage = "")
{
           IWebHelper webHelperFromPassedContext = new WebHelper(httpContext);

            var log = new Log()
            {
                LogLevel = logLevel,
                ShortMessage = shortMessage,
                FullMessage = fullMessage,
                IpAddress = webHelperFromPassedContext.GetCurrentIpAddress(),
                PageUrl = webHelperFromPassedContext.GetThisPageUrl(),
                ReferrerUrl = webHelperFromPassedContext.GetUrlReferrer(),
                CreatedOnUtc = DateTime.UtcNow
            };

            this.logRepository.Insert(log);
            return log;
}


my call in the error handle attribute is now:


this.logger.InsertLog(LogLevel.Error, "An exception occured",filterContext.HttpContext,filterContext.Exception.Message);


I think this is what Dharmik meant. Hope this helps.

br,

michael
9 years ago
Why is this still not fixed? (v 3.50)

The following code still throws the error.


if (String.IsNullOrEmpty(result) && _httpContext.Request.UserHostAddress != null)
{
    result = _httpContext.Request.UserHostAddress;
}
9 years ago
See this post
7 years ago
Same problem still in v3.8 :-(
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.