gpt4 book ai didi

asp.net-mvc-4 - 如何在mvc中获取用户IP地址

转载 作者:行者123 更新时间:2023-12-04 18:07:34 31 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to get the public IP address of a user in C#

(16 个回答)


7年前关闭。




我正在使用 Mvc4,
我想获取使用我网站的用户的 IP 地址。
Based on this link
我可以获得用户主机地址,但我想获得确切的用户 IP 地址

最佳答案

取决于你所在的地方。

Controller :

ControllerContext.HttpContext.Request.UserHostAddress;

Razor View :
@Request.UserHostAddress

模型:

不要使用 System.Web.HttpContext,因为它很难进行单元测试,如果不是不可能的话。相反,通过您的 Controller 传递值。

Html 助手:
public static MvcHtmlString Ip(this HtmlHelper html)
{
string html = html.ViewContext.RequestContext.HttpContext.Request.UserHostAddress;
return MvcHtmlString.Create(html);
}

请记住,由于示例的简单性,我没有进行任何空检查。

关于asp.net-mvc-4 - 如何在mvc中获取用户IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23335505/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com