I'm completely new to the ASP.NET MVC stack and I'd like to know what's going on with the simple Page object and the Request ServerVariables object?
Basically, I want to extract the IP address of the client PC, but I can't understand how the current MVC structure changes this.
As far as I know, most variable objects have been replaced by HttpRequest variants.
Is anyone willing to share some resources? There is truly a ton of stuff to learn in the ASP.NET MVC world. :)
For example, I have a static class with a current function. How can I achieve the same results using ASP.NET MVC?
public static int getCountry(Page page) { return getCountryFromIP(getIPAddress(page)); } public static string getIPAddress(Page page) { string szRemoteAddr = page.Request.ServerVariables["REMOTE_ADDR"]; string szXForwardedFor = page.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; }
How to call this function from the controller page?
Request.ServerVariables["REMOTE_ADDR"]
Should work - directly in the view or in the controller action method body (Request is a property of the Controller class in MVC, not Page). p>It's working.. but you have to publish on real IIS not virtual IIS.
The simple answer is to use the HttpRequest.UserHostAddress property .
Example:From inside the controller:
Example:From helper class:
However, if the request has been sent by one or more proxy servers 传递> then the IP address property HttpRequest.UserHostAddress returned will be the last one to relay the request The IP address of a proxy server.
Proxy serverscan use the de facto standard to place the client's IP address in the X-Forwarded-For HTTP header. In addition to the fact that the request has an X-Forwarded-For header, there is also no guarantee that X-Forwarded-For has not been spoofed.
Original answer
The code above provides the client's IP address without having to look up the collection. The Request property is available in the controller (or view). So instead of passing the Page class to your function, you can pass a Request object to get the same result: