栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在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;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/452088.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号