[英]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:这是我获取 IP 地址的方法:
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?现在我需要在我的一个视图页面中使用 IP 地址。所以我想将它用作 ViewData 如何在我的控制器上使用它? 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.
我只想在我的方法之一中使用这个 GetUserIpAddress 方法。所以我必须从查看数据中使用。 I know I had to write:
我知道我必须写:
var userIp = ???.GetUserIpAddress();
ViewData["userIp"] = userIp;
How can I use it?我怎样才能使用它?
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.如果您不想或不能使用视图模型,您可以使用
ViewBag
或ViewData
将值从控制器传递到视图。 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>
I Find My Mistake.我发现我的错误。 I have to write :
我必须写:
var userIp = _articleService.GetUserIpAddress();
ViewData["UserIp"] = userIp;
Because I have to call in from service因为我必须从服务中调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.