仅对ASP.NET网页进行本地访问

时间:2010-07-22 01:58:35

标签: asp.net web-config authorization

是否可以配置web.config以授权页面仅在本地读取(概念类似于RemoteOnly功能的错误消息)。

1 个答案:

答案 0 :(得分:0)

您可以在您希望的页面上查看此内容。下面是我编写的示例代码,用于检查用户是否为本地用户。

override protected void OnInit(EventArgs e)
{
    if (!IsUserLocal())
    {
        Response.Redirect("~/");
        return;
    }

    base.OnInit(e);
}

public bool IsUserLocal()
{
    string userHostAddress = Request.ServerVariables["REMOTE_HOST"].ToString();

    if (string.IsNullOrEmpty(userHostAddress))
    {
        return false;
    }
    return (((userHostAddress == "127.0.0.1") || (userHostAddress == "::1")) || (userHostAddress == LocalAddress()));
}


public string LocalAddress()
{
    IServiceProvider provider = (IServiceProvider)HttpContext.Current;
    HttpWorkerRequest wr = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));

    return wr.GetLocalAddress();
}