【发布时间】:2011-12-14 22:10:23
【问题描述】:
我有一个每天执行的 asp.net 页面 (c#)。
我想知道是否有一种方法允许它仅在与服务器相同的 ip 请求时才执行。这意味着,如果另一个 ip 运行该页面,则不会发生任何事情或将被重定向。
【问题讨论】:
标签: c# asp.net access-control
我有一个每天执行的 asp.net 页面 (c#)。
我想知道是否有一种方法允许它仅在与服务器相同的 ip 请求时才执行。这意味着,如果另一个 ip 运行该页面,则不会发生任何事情或将被重定向。
【问题讨论】:
标签: c# asp.net access-control
您可以使用Request.IsLocal 来检查请求是否是本地的。
【讨论】:
以下也适用于低于 2.0 的框架(但如果可用,HttpRequest.IsLocal 更可取)。
C#
public static void redirectIfNotServer(string redirectUrl)
{
// Look for a proxy address first
var IP = HttpContext.Current.Request.ServerVariables("HTTP_X_FORWARDED_FOR");
//Trim and lowercase IP if not null
if ((IP != null)) {
IP = IP.ToLower().Trim;
}
if (IP == null || (IP.Equals("unknown"))) {
//If IP is null use different detection method, else pull the correct IP from list.
IP = HttpContext.Current.Request.ServerVariables("REMOTE_ADDR").ToLower().Trim();
}
List<string> IPs = null;
if (IP.IndexOf(",") > -1) {
IPs = IP.Split(',').ToList();
} else {
IPs = new string[] { IP }.ToList();
}
var serverIP = HttpContext.Current.Request.ServerVariables("LOCAL_ADDR");
var ipIsServerIp = (from ipAddress in IP swhere ipAddress == serverIP).Any();
if (!ipIsServerIp) {
HttpContext.Current.Response.Redirect(redirectUrl);
}
}
VB.NET
Public Shared Sub redirectIfNotServer(ByVal redirectUrl As String)
' Look for a proxy address first
Dim IP = HttpContext.Current.Request.ServerVariables("HTTP_X_FORWARDED_FOR")
'Trim and lowercase IP if not null
If Not IP Is Nothing Then
IP = IP.ToLower().Trim
End If
If IP Is Nothing OrElse (IP.Equals("unknown")) Then
'If IP is null use different detection method, else pull the correct IP from list.
IP = HttpContext.Current.Request.ServerVariables("REMOTE_ADDR").ToLower().Trim
End If
Dim IPs As List(Of String)
If IP.IndexOf(",") > -1 Then
IPs = IP.Split(","c).ToList
Else
IPs = New String() {IP}.ToList
End If
Dim serverIP = HttpContext.Current.Request.ServerVariables("LOCAL_ADDR")
Dim ipIsServerIp = (From ipAddress In IPs Where ipAddress = serverIP).Any
If Not ipIsServerIp Then
HttpContext.Current.Response.Redirect(redirectUrl)
End If
End Sub
【讨论】:
使用 HttpRequest 对象上的UserHostAddress 属性获取用户地址。
使用LOCAL_ADDR 变量和ServerVariables 属性从请求对象中获取服务器地址。
通过检查IsLocal 属性,Fernando 有更好的解决方案。
【讨论】:
可以查询HttpRequest的IsLocal属性
http://msdn.microsoft.com/en-us/library/system.web.httprequest.islocal.aspx
【讨论】:
这个:
Request.ServerVariables["REMOTE_ADDR"]
将为您获取远程 ip,然后将其与您的服务器 ip 或“本地主机”进行比较
【讨论】: