如何在ASP.NET MVC中获取客户端的IP地址?

如何在ASP.NET MVC中获取客户端的IP地址?,第1张

如何在ASP.NET MVC中获取客户端的IP地址

简单的答案是使用HttpRequest.UserHostAddress属性。

示例: 从控制器内部:

using System;using System.Web.Mvc;namespace Mvc.Controllers{    public class HomeController : ClientController    {        public ActionResult Index()        { string ip = Request.UserHostAddress; ...        }    }}

示例: 在帮助器类中:

using System.Web;namespace Mvc.Helpers{    public static class HelperClass    {        public static string GetIPHelper()        { string ip = HttpContext.Current.Request.UserHostAddress; ..        }    }}

但是,
如果请求已被一个或多个代理服务器传递,则HttpRequest.UserHostAddress属性返回的IP地址将是中继该请求的最后一个代理服务器的IP地址。

代理服务器 可以 使用 事实上的 标准,将客户的IP地址放在X-Forwarded-
For
HTTP标头中。除了不能保证请求具有X-
Forwarded-For标头之外,也不能保证X-Forwarded-For没有被
SPOOFED


原始答案

Request.UserHostAddress

The above pre provides the Client’s IP address without resorting to looking
up a collection. The Request property is available within Controllers (or
Views). Therefore instead of passing a Page class to your function you can
pass a Request object to get the same result:

public static string getIPAddress(HttpRequestbase request){    string szRemoteAddr = request.UserHostAddress;    string szXForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];    string szIP = "";    if (szXForwardedFor == null)    {        szIP = szRemoteAddr;    }    else    {        szIP = szXForwardedFor;        if (szIP.IndexOf(",") > 0)        { string [] arIPs = szIP.Split(','); foreach (string item in arIPs) {     if (!isPrivateIP(item))     {         return item;     } }        }    }    return szIP;}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5427614.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-11
下一篇2022-12-11

发表评论

登录后才能评论

评论列表(0条)

    保存