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

150 Views Asked by At

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?

2

There are 2 best solutions below

0
hasti.au On BEST ANSWER

I Find My Mistake. I have to write :

 var userIp = _articleService.GetUserIpAddress();

        ViewData["UserIp"] = userIp;

Because I have to call in from service

8
Gabe On

You can use a ViewBag or ViewData to pass values from a controller to a view if you don't want to or can't use a view model. Here is an example of both:

public IActionResult YourAction()
{
    // With a ViewBag
    ViewBag.UserIp = "178.94.293.29";

    // With a ViewData
    ViewData["UserIp"] = "178.94.293.29";

    return View();
}

Then in your view, you can access the data like this:

<h1>Title</h1>
<span>Get ViewBag value: @ViewBag.UserIp</span>
<span>Get ViewData value: @ViewData["UserIp"]</span>