ASP.net页面只允许在服务器上执行?

时间:2011-10-25 12:45:16

标签: c# asp.net access-control

我有一个每天执行的asp.net页面(c#)。

我想知道是否有办法只允许它在与服务器相同的ip请求时执行。这意味着,如果另一个ip运行页面,则不会发生任何事情,或者它将被重定向。

5 个答案:

答案 0 :(得分:7)

您可以使用Request.IsLocal检查请求是否为本地请求。

答案 1 :(得分:2)

答案 2 :(得分:2)

以下工作也使用低于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

答案 3 :(得分:1)

此:

Request.ServerVariables["REMOTE_ADDR"] 

将获取远程ip,然后将其与您的服务器ip或“localhost”

进行比较

答案 4 :(得分:1)

使用HttpRequest对象上的UserHostAddress属性获取用户地址。

LOCAL_ADDR变量与ServerVariables属性一起使用,以从请求对象中获取服务器地址。

通过查看IsLocal属性,费尔南多有更好的解决方案。