[英]asp.net c# ip address lost after postback?
One of my functions in a class is called GetIpAddress() which returns the following string: System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] 我在类中的一个函数称为GetIpAddress(),该函数返回以下字符串:System.Web.HttpContext.Current.Request.ServerVariables [“ REMOTE_ADDR”]
This all works well in regular page loads and gets my ip address, but when i for example let a user place a comment, then the ip address is lost after postback and i get an empty string returned. 这一切在常规页面加载中都能很好地工作并获取我的IP地址,但是例如当我让用户发表评论时,回发后IP地址就会丢失,并且我会返回一个空字符串。
Am I missing something here maybe? 我在这里想念什么吗?
Kind regards, Mark 亲切的问候,马克
Use these ones: 使用这些:
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; // a user is going through a proxy server
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
HttpContext.Current.Request.UserHostAddress;
Some explanation: REMOTE_ADDR The IP address of the remote host making the request. 一些说明:REMOTE_ADDR发出请求的远程主机的IP地址。
REMOTE_HOST The name of the host making the request. REMOTE_HOST发出请求的主机的名称。 If the server does not have this information, it will set REMOTE_ADDR and leave this empty.
如果服务器没有此信息,它将设置REMOTE_ADDR并将其留空。
Do you have it wrapped in something like this? 你有包裹在这样的东西吗?
if (!Page.IsPostBack) {
GetIpAddress()
}
You need to either call the function every time, or store it in a Shared variable. 您需要每次调用该函数,或将其存储在Shared变量中。
Another option (As @Marc mentioned) would be to simply call Request.UserHostAddress
instead of GetIpAddress
... it's almost the same amount of typing, but you don't have to have a custom function for it. 另一个选择(如@Marc所述)是简单地调用
Request.UserHostAddress
而不是GetIpAddress
...它的键入量几乎相同,但是您不必为此提供自定义功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.