2013-03-25 45 views
1

是否有一種方法可以編寫一些代碼,用於將每個請求執行到.aspx或.cshtml頁面的asp.net 4.5 以外使用基頁面類。這是一個非常大的項目,並且對所有頁面進行更改以使用基本頁面是一場噩夢。此外,我不知道這將如何做一個cshtml頁面,因爲他們沒有一個類。爲ASP.NET的每個請求(aspx和cshtml)執行一些代碼

我們是否可以使用Application_BeginRequest並且僅針對aspx和cshtml文件,因爲網站是以集成模式運行的。

基本上,我必須檢查訪問該網站的用戶是否具有針對數據庫的特定IP地址,如果是,則允許訪問,否則重定向。

我們使用IIS8和ASP.Net 4.5和ASP.Net剃刀網頁

回答

1

而且我不知道怎麼會變成這樣一個CSHTML頁面完成,因爲他們沒有一個類。

您可以放置​​一個_ViewStart.cshtml文件,其內容將在每個請求上執行。

或者你可以寫一個custom Http Module

public class MyModule: IHttpModule 
{ 
    public void Init(HttpApplication app) 
    { 
     app.BeginRequest += new EventHandler(OnBeginRequest); 
    } 

    public void Dispose() 
    { 

    } 

    public void OnBeginRequest(object s, EventArgs e) 
    { 
     // this code here's gonna get executed on each request 
    } 
} 

,然後簡單地註冊這個模塊在你的web.config:

<system.webServer> 
    <modules> 
     <add name="MyModule" type="SomeNamespace.MyModule, SomeAssembly" /> 
    </modules> 
    ... 
</system.webServer> 

,或者如果您在經典模式下運行:

<system.web> 
    <httpModules> 
     <add name="MyModule" type="SomeNamespace.MyModule, SomeAssembly" /> 
    </httpModules> 
</system.web> 

基本上,我必須檢查訪問該網站的用戶是否具有針對數據庫的特定IP地址 ,如果是,則允許訪問 否則重定向。

裏面的OnBeginRequest方法,你可以獲取當前用戶IP:

public void OnBeginRequest(object sender, EventArgs e) 
    { 
     var app = sender as HttpApplication; 
     var request = app.Context.Request; 
     string ip = request.UserHostAddress; 
     // do your checks against the database 
    } 
+0

謝謝Darin ...那完美的作品:) – 2013-03-25 08:46:48

1

Asp.net MVC過濾器是專爲這一目的。

你會實現ActionFilterAttribute這樣的(也許把這個新類的過濾器文件夾在你的web應用程序的解決方案):

public class IpFilter : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     string ip = filterContext.HttpContext.Request.UserHostAddress; 

     if(!testIp(ip)) 
     { 
      if (true /* You want to use a route name*/) 
       filterContext.Result = new RedirectToRouteResult("badIpRouteName"); 
      else /* you want an url */ 
       filterContext.Result = new RedirectResult("~/badIpController/badIpAction"); 
     } 

     base.OnActionExecuting(filterContext); 
    } 
    private bool testIp(string inputIp) 
    { 
     return true /* do you ip test here */; 
    } 
} 

然後,你必須來裝飾,將像這樣使用IPFilter進行ipcheck任何行動:

[IpFilter] 
    public ActionResult AnyActionWhichNeedsGoodIp() 
    { 
     /* do stuff */ 
    } 
相關問題