簡體   English   中英

返回 IP 地址作為 ASP .NET Core 上的視圖數據

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

我有這個模型

  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; }

}

這是我獲取 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;

    }

現在我需要在我的一個視圖頁面中使用 IP 地址。所以我想將它用作 ViewData 如何在我的控制器上使用它? 我有幾種方法,它的視圖有另一個視圖模型。 我只想在我的方法之一中使用這個 GetUserIpAddress 方法。所以我必須從查看數據中使用。 我知道我必須寫:

 var userIp = ???.GetUserIpAddress();

        ViewData["userIp"] = userIp;

我怎樣才能使用它?

如果您不想或不能使用視圖模型,您可以使用ViewBagViewData將值從控制器傳遞到視圖。 這是兩者的示例:

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

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

    return View();
}

然后在您的視圖中,您可以像這樣訪問數據:

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

我發現我的錯誤。 我必須寫:

 var userIp = _articleService.GetUserIpAddress();

        ViewData["UserIp"] = userIp;

因為我必須從服務中調用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM