asp.net-coremodelreturnipviewdata

Return IP Address as a View Data on ASP .NET Core


I have this Model

  public class ArticleVote:BaseEntity
{

    [Display(Name = "UserId")]
    public long? UserId { get; set; }

    public string UserIp { get; set; }

    [Display(Name = "ArticleId")]
    public long ArticleId { get; set; }

}

and this is my method for get IP Address:

     public string GetUserIpAddress()
    {

        string strHostName = System.Net.Dns.GetHostName();
        IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
        IPAddress[] addr = ipEntry.AddressList;
        string ip = addr[1].ToString();

        return ip;

    }

Now I need IP Address in one of my view page .So I want to use it as a ViewData How can I use it on my Controller? I have several method and its view has another View Model. I want to use just this GetUserIpAddress Method inside one of my method.so I have to use from View Data. I know I had to write:

 var userIp = ???.GetUserIpAddress();

        ViewData["userIp"] = userIp;

How can I use it?


Solution

  • I Find My Mistake. I have to write :

     var userIp = _articleService.GetUserIpAddress();
    
            ViewData["UserIp"] = userIp;
    

    Because I have to call in from service