简单的答案是使用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;}


