如何限制只访问localhost的页面?

时间:2012-08-09 08:30:15

标签: asp.net security localhost

asp.net中是否有办法限制只能从localhost访问网页?

3 个答案:

答案 0 :(得分:12)

     if (!HttpContext.Current.Request.IsLocal)
     { 
       Response.Status = "403 Forbidden";
       Response.End();
     }

答案 1 :(得分:6)

如果您想为“网页”执行此操作,那么我将使用IsLocal,但如果您需要子目录解决方案,我将使用Url Rewrite 2. http://www.microsoft.com/web/gallery/install.aspx?appid=urlrewrite2。如果你还没有安装它,那就去拿它,因为它非常有用。我相信它将成为IIS8的标准。

然后将其添加到<system.webServer/>

下的web.config中
<rewrite>
 <rules>
    <!-- if this rule matches stopProcessing any further rules -->
    <rule name="Block Remote Access to Admin" stopProcessing="true" patternSyntax="ECMAScript" enabled="true">
      <!-- specify secure folder matching trailing / or $ == end of string-->
      <match url="projects(/|$)" ignoreCase="true" />
      <conditions logicalGrouping="MatchAll">
        <!-- Allow local host -->
        <add input="{REMOTE_ADDR}" pattern="localhost" ignoreCase="true" negate="true" />
        <add input="{REMOTE_ADDR}" pattern="127.0.0.1" negate="true" />
        <add input="{REMOTE_ADDR}" pattern="::1" negate="true" />
      </conditions>
      <!-- by default, deny all requests. Options here are "AbortRequest" (drop connection), "Redirect" to a 403 page, "CustomResponse", etc.  -->
      <action type="CustomResponse" statusCode="403" statusDescription="Forbidden" statusReason="Access to this URL is restricted"/>
      <!-- or send the caller to an error page, home page etc
           <action type="Redirect" url="/public/forbidden.htm" redirectType="Temporary" />
      -->
    </rule>
  </rules>
</rewrite>

答案 2 :(得分:0)

这可能是一个解决方案:

protected void Page_Load(object sender, EventArgs e)
{
    string localhost = Request.Url.Authority;
    if (localhost.IndexOf("localhost") != 0)
        Response.Redirect("defalut.aspx");
}